我目前正在做一些非常基础的事情,但我遇到了困难。我想在二维数组中获取一个随机索引,并在每次 for 循环翻转时将其递增 1。
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]]);
为什么这个 for 循环会将所有索引设置为 30,000?我是否错误地使用了 JavaScript 数组?
谢谢。
最佳答案
你在做什么
您似乎误解了您正在做的事情的语法。目前相当于
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`
然后你在做
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"
你可能想做什么
看起来您实际上想要一个 Array 6
Array 每个 6
Numbers;构建你最喜欢的方式
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]
];
然后你的循环是
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..
}
然后说你想知道有多少次 dieOne = 1, dieTwo = 3,你会看看
dice[1][3]; // count the brackets again.
关于javascript - 在 JavaScript 中递增多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19737555/