Select random item from array - javascript

I am trying to make a game for my two girls. It randomly selects an adjective and a noun, then displays the words for them to act out.
I can get the random words to print to the console, but now I need them to appear in the html.
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
var randomAdj = (["happy", "sad", "bouncy", "silly"].sample());
var randNoun = (["monkey", "butterfly", "puppy"].sample());
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
The last two lines aren't working for me (#adj and #noun are span ids used in the html).
I am only a couple of weeks into learning, so I might be missing something super obvious here.

The random part should work (keep in mind that modifying the prototypes is not a good practice, tho), but you have two syntax errors:
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
Pass "adj" and "noun" as strings:
document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;
You don't need the # snippet in the getElementById call.
Also note that you you are using randomNoun but you declared randNoun. Here is the working code and example:
function randomItem(arr){
return arr[Math.floor(Math.random()*arr.length)];
}
var randomAdj = randomItem(["happy", "sad", "bouncy", "silly"]);
var randomNoun = randomItem(["monkey", "butterfly", "puppy"]);
document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;
<span id="adj"></span>
<span id="noun"></span>

worng
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
use
document.getElementById("adj").innerHTML = randomAdj;
document.getElementById("noun").innerHTML = randomNoun;

Related

Iterating thorugh array but always returning last value

I am iterating thorugh an array and trying to get different data for each object in array but I end up with same data, if i have three products in billBodies i end up with three item that have the same value (for example i have 3 candies, 2 coffees, and 4 candy bars result I get is 4 candy, 4 candy, 4 candy).
Hope anyone can help i tried to search similar problems but didn't find it though...
for (let bill of dataOfBillHeader.billBodies) {
console.log(dataOfBillHeader)
console.log(this.productToShowOnView)
this.productToShowOnView.cipher = bill.product.cipher;
this.productToShowOnView.name = bill.product.name;
this.productToShowOnView.measure = bill.product.measure;
this.productToShowOnView.count = bill.product.count;
this.productToShowOnView.price = bill.product.price;
this.productToShowOnView.id = dataOfBillHeader.id;
this.productToShowOnView.count = bill.count;
this.productToShowOnView.quantity = bill.quantity;
this.productToShowOnView.discount = bill.discount;
this.productToShowOnView.discountAmount = bill.discountAmount;
this.productToShowOnView.totalPrice = bill.totalPrice;
console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
const newBasket = this.productsInBasket;
this.productsInBasket.push(this.productToShowOnView);
this.productsInBasket = [...newBasket];
this.cd.detectChanges();
}
Well, you are just pushing the same object (reference) in there over and over, namely this.productToShowOnView. Why are you using this.productToShowOnView? Why not a local constant. And with a little magic you can make it a bit smaller, although I don't understand why you would go from one product data format to another one...:
const newBasket = [...this.productsInBasket];
for (let bill of dataOfBillHeader.billBodies) {
const product = {
// no need to get all those individually
...bill.product,
...bill,
//this is weird, all products have the same id?
id: dataOfBillHeader.id,
};
newBasket.push(product);
}
this.productsInBasket = newBasket;
this.cd.detectChanges();

Multidimensional array in javasscript

I'm learning from the book JavaScript for Dummies, and from the following code, it says
console.log( bestAlbumsByGenre[0][1] ) //will output: Patsy Cline:Sentimentally Yours
var bestAlbumsByGenre = []
bestAlbumsByGenre[0] = “Country”;
bestAlbumsByGenre[0][0] = “Johnny Cash: Live at Folsom Prison”
bestAlbumsByGenre[0][1] = “Patsy Cline: Sentimentally Yours”;
bestAlbumsByGenre[0][2] = “Hank Williams: I’ m Blue Inside”;
but in the console the output is: "o". Why is that, and what am I doing wrong?
You seem to have mixed up two different exercises.
The following line is resulting in the error:
bestAlbumsByGenre[0] = "Country";
I've cleaned up the code to make it work.
However, I think I would prefer an object, where each key represents the genre, and their value is an array.
// Define the outer array
const bestAlbumsByGenre = [];
// Set the first element of the array as an array
bestAlbumsByGenre[0] = [];
// Add items to the first element (the array)
bestAlbumsByGenre[0][0] = "Johnny Cash: Live at Folsom Prison"
bestAlbumsByGenre[0][1] = "Patsy Cline: Sentimentally Yours";
bestAlbumsByGenre[0][2] = "Frank Williams: I’ m Blue Inside";
console.log(bestAlbumsByGenre[0][1]);
// Alternative approach
const reallyBestAlbumsByGenre = {
rock: [],
};
reallyBestAlbumsByGenre.rock.push("Johnny Cash: Live at Folsom Prison");
reallyBestAlbumsByGenre.rock.push("Patsy Cline: Sentimentally Yours");
reallyBestAlbumsByGenre.rock.push("Frank Williams: I’ m Blue Inside");
console.log( reallyBestAlbumsByGenre.rock[1] );
Since you want to organize albums by genre, it would make more sense to create an object with the genre as a key:
var bestAlbumsByGenre = {
"Country": [
"Johnny Cash: Live at Folsom Prison",
"Patsy Cline: Sentimentally Yours",
"Hank Williams: I’m Blue Inside",
]
}
Your not actually accessing a two dimensional array, but you are accessing the second character of a string.
Your are initializing a 1 dimensional array of string when you do:
When you did the following:
var bestAlbumsByGenre = [];
bestAlbumsByGenre[0] = "Country";
You assigned a string to the first element.
Subsequently, the other statements did nothing.
Fix
The following fixes your error:"
var bestAlbumsByGenre = [[]]
bestAlbumsByGenre[0][0] = "Country";

javascript rearrange arrays in permutations for jquery selectors

Not sure of the best title for this question so any revision suggestions welcome...
say i have 1 javascript array that look like this:
group[g1] = [v1,v2,v3]
group[g2] = [a1,a2,a3]
group[g3] = [b1,b2,b3]
and so on... ad infinitum
and i want to rearrange this to get
newgroup[z] = [v1,a1,b1]
newgroup[y] = [v1,a1,b2]
newgroup[x] = [v1,a1,b3]
newgroup[w] = [v1,a2,b1]
newgroup[v] = [v1,a2,b2]
newgroup[u] = [v1,a2,b3]
newgroup[t] = [v1,a3,b1]
newgroup[s] = [v1,a3,b2]
newgroup[r] = [v1,a3,b3]
newgroup[q] = [v2,a1,b1]
newgroup[p] = [v2,a1,b2]
newgroup[o] = [v2,a1,b3]
newgroup[n] = [v2,a2,b1]
newgroup[m] = [v2,a2,b2]
newgroup[h] = [v2,a2,b3]
newgroup[g] = [v2,a3,b1]
newgroup[f] = [v2,a3,b2]
newgroup[d] = [v2,a3,b3]
newgroup[q] = [v3,a1,b1]
newgroup[p] = [v3,a1,b2]
newgroup[o] = [v3,a1,b3]
newgroup[n] = [v3,a2,b1]
newgroup[m] = [v3,a2,b2]
newgroup[h] = [v3,a2,b3]
newgroup[g] = [v3,a3,b1]
newgroup[f] = [v3,a3,b2]
newgroup[d] = [v3,a3,b3]
i.e.. making a list of all the permutations of the different ways of grouping those items
Ideally this would be dynamic so that no matter how many groups there were of elements in each group array.. it would also work.
I could then join in newsgroup and link them all together to make one large selector for jquery.
Please help...its beyond me now!
I realised I was looking for a Cartesian product of my original array.. And found the result here.. Lazy Cartesian product of arrays (arbitrary nested loops)… god I love this site

viewer.loadImageFromJSON with variable not working

I have the following javascript that works perfectly good (with jquery):
function(test) {
var neuroimages = viewer.loadImageFromJSON('../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold');
return neuroimages;
};
Now I want to use a variable (lets say picture) instead of the '../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold' and format the code accordingly:
function(test) {
picture = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
neuroimages = viewer.loadImageFromJSON(picture);
return neuroimages;
};
This does not work.
Neither does this:
function(test) {
pic1 = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
pic2 = "'neg_subj_val_5'";
pic3 = "'hot and cold'";
neuroimages = viewer.loadImageFromJSON(pic1, pic2, pic3);
return neuroimages;
};
What am I doing wrong there?
I tried google and several sites with no success. Not to mention that I'm quiet a beginner with Java and already near insanity.
You are almost right with the second example. Here you should only specify one piece of data for each variable (at least in your case, but there are ways to specify many pieces of data in a single variable such as arrays and objects). Also you only need to have one set of quotes surrounding each string (doesn't matter whether they are single or double quotes as long as they match). Also, precede your variables with the 'var' keyword unless you want them to be global.
function(test) {
var pic1 = "../data/new/res_neg_subj_val_5.nii.json";
var pic2 = "neg_subj_val_5";
var pic3 = "hot and cold";
neuroimages = viewer.loadImageFromJSON(pic1, pic2, pic3);
return neuroimages;
};
Making your first attempt work is a little more tricky as you are passing an array to a function that expects three distinct variables. You do it like this:
function(test) {
var picture = ['../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'];
neuroimages = viewer.loadImageFromJSON.apply(viewer, picture);
return neuroimages;
};
You're trying to initialize an array here, but you need to have a string instead. Try changing this:
picture = "'../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'";
to:
picture = "'../data/new/res_neg_subj_val_5.nii.json';
You are not specifying if viewer.loadImageFromJSON() can accept an array, instead of a string. If it can, you could do something like:
picture = ['../data/new/res_neg_subj_val_5.nii.json', 'neg_subj_val_5', 'hot and cold'];
Check here on how to initialize arrays in Javascript:
http://www.w3schools.com/js/js_obj_array.asp
If you need more information on the issue, please attach the code for loadImageFromJSON(), so that we know how this function handles input and output

JS/Jquery - using variable in json selector

I need to use a variable when selecting data from a json source like this.
The json is retrieved with jquery getJSON().
"prices":[{
"fanta":10,
"sprite":20,
}]
var beverage = fanta;
var beverage_price = data.prices.beverage;
Now beverage_price = 10
var beverage = sprite;
var beverage_price = data.prices.beverage;
Now beverage_price = 20
When I try to do it like in the examples, the script tries to look up the beverage entry in prices.
Thanks a lot!!
You can access it like:
var beverage = 'fanta';
var beverage_price = data.prices[0][beverage];
As VisioN mentioned in the comment, data.prices is an array, you need to access its first element with [0] which contains prices { "fanta":10, "sprite":20}
here is the working example : http://jsfiddle.net/2E8AH/
Or else you can make data.prices an object like below : (if it is in your control)
var data = {
"prices" :
{
"fanta":10,
"sprite":20,
}
};
and can access without [0] like this : http://jsfiddle.net/Y8KtT/1/

Categories

Resources