Removing random element from an array /Javascript - javascript

I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.

You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.

Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);

You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}

#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));

Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}

Related

Printing an object within an array showing as blank

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.
You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

change the text of a label and in js and use it from code behind?

I created a list of buttons from code behind, and append them on some div, how ever each button has an onclick java script function
here is how I did it:
string[] messages = CM.GetMessages(Session["USER_EMAIL"].ToString()).Split(new string[] { "$STARTCHAT$" }, StringSplitOptions.None);
string[] usersalone = CM.GetChaters(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
string[] username = CM.GetUserNames(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
for (int i = messages.Length-2; i>=0; i--)
{
Button b = new Button();
b.ID = Session["USER_EMAIL"].ToString()+username[i];
b.Text = "Chat With: " + usersalone[i] ;
b.Width = 250;
b.Height = 100;
b.OnClientClick = "return DisplayMessage('" + messages[i+1] + "','" + username[i] + "','" + Session["USER_EMAIL"].ToString() + "')";
b.Style.Add("background-color", "rgb(246, 246, 246)");
// lblChatwith.Text = username[i];
NewMsgNotArrow.Controls.Add(b);
}
and here is my java script function:
function DisplayMessage(messages, from, username) {
document.getElementById("AllMessages").innerText ="";
document.getElementById("DivDisplayMessage").style.visibility = "visible";
document.getElementById("lblChatwith").innerText = from;
var MessageForEachUser = messages.split("$SAMECHATNEWTEXT$");
for (var i = 0; i < MessageForEachUser.length; i++)
{
var ck = MessageForEachUser[i].indexOf("$" + from.toUpperCase() + "$") > -1;
if (ck == true) {
document.getElementById("AllMessages").innerText += from.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + from.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
if (ck == false) {
document.getElementById("AllMessages").innerText += username.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + username.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
document.getElementById("AllMessages").innerText += MessageForEachUser[i] + "\n______________________________________________________" + "\n";
}
return false;
}
every thing is working well but, when i want to use one of the labels like "lblchatwith" from code behind it return an empty string.

JavaScript addition issue

So, i'm adding 2 characters 4 levels together (hp, attack, strength and defense) and then comparing them. However I am having a problem. when the numbers are added together they're added together as a string so it outputs as follows. 9060951/99709940 instead of 246 (90+60+95+1)/308 (99+70+99+40). Here is what I am doing.
function calculate(player1, player2) {
var total1 = player1.getTotal();
var total2 = player2.getTotal();
var differencePercentage;
if(total1 > total2) {
differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
} else {
differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
}
var percentage = differencePercentage;
return percentage;
}
function Player(hp, attack, strength, defense) {
this.hp = parseInt(hp);
this.attack = parseInt(attack);
this.strength = parseInt(strength);
this.defense = parseInt(defense);
this.getTotal = function() {
var total = 0;
total = hp + attack + strength + defense;
return total;
}
}
Why is this happening?
You are parsing the Ints into this.hp, this.attack etc. in your Player function but not into the getTotal function
Try this
this.getTotal = function() {
var total = 0;
total = this.hp + this.attack + this.strength + this.defense;
return total;
}

Need some improvement in xml display

i have implemented this code to display xml in html using javascript
current output
Need something like
Here is my code
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
var f = false;
if (n.nodeType !== 3) {
str += '<br><<span class="nn">' + n.nodeName + '</span>>';
if (n.hasChildNodes()) {
f = true;
str += parseXML(n, s++);
}
str += '</<span class="nn">' + n.nodeName + '</span>>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
if (f) {
str += '<br>';
}
}
var str = str.replace(/(<br>)+/g, '<br>');
return str;
}
how i call this
R : xml object
s : initial 0 (i am passing this so that i can display xml as hirarchical view)
Output in second
- is not required
i have post second out as it can be seen while opening xml document in firefox
please ask if any doubt
I solved it myself.
Updated code with the solution
var pre = 0;
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
if (n.nodeType !== 3) {
str += '<br>' + gs(s) + '<b><</b><span class="nn">' + n.nodeName + '</span><b>></b>';
if (n.hasChildNodes()) {
str += parseXML(n, s + 1);
}
if (pre !== 3) {
str += '<br>' + gs(s);
}
str += '<b><</b>/<span class="nn">' + n.nodeName + '</span><b>></b>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
pre = n.nodeType;
}
return str;
}

Categories