I'm currently working on something very basic but I am having a hard time. I would like to get a random index in a two dimensional array and increment it by one every time the for-loop turns over.
var dice = [[],[]];
// Get totals.
for(var i = 0; i < 30000; i++) {
var dieOne = Math.floor(Math.random() * 6 + 1);
var dieTwo = Math.floor(Math.random() * 6 + 1);
dice[[dieOne][dieTwo]]++;
}
// All index values equal 30,000 for some reason
alert(dice[[1][3]]);
Why would this for loop set all indexes to 30,000? Am I using JavaScript arrays incorrectly?
Thanks.
What you're doing
It seems like you're misunderstanding the syntax of what you're doing. It is currently equivalent to
var dieOne = Math.floor(Math.random() * 6 + 1);
var dieTwo = Math.floor(Math.random() * 6 + 1);
var foo;
foo = dieOne; // a number
foo = [foo]; // an array with one number in it
foo = foo[dieTwo]; // probably undefined, unlikely case of `dieTwo = 0`
// which would give back `dieOne`
dice[foo] = dice[foo] + 1; // most likely trying to add 1 to property `undefined`
Then later you're doing
foo = [1]; // an array length 1
foo = foo[3]; // undefined, it doesn't have an item here
foo = dice[foo]; // = dice[undefined] = undefined
alert(foo); // alerting "undefined"
What you probably want to be doing
It looks like you actually want an Array of 6
Arrays each of 6
Numbers; construct your favourite way
var dice = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
];
Then for your loop to be
var dieOne, dieTwo, i;
for(i = 0; i < 30000; ++i) {
dieOne = Math.floor(Math.random() * 6); // indices start at 0 and
dieTwo = Math.floor(Math.random() * 6); // 6 of them means max is 5
dice[dieOne][dieTwo]++; // count the brackets here..
}
then say you want to know how many times you had dieOne = 1, dieTwo = 3, you would look at
dice[1][3]; // count the brackets again.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments