javascript - 在 JavaScript 中递增多维数组

标签 javascript multidimensional-array

我目前正在做一些非常基础的事情,但我遇到了困难。我想在二维数组中获取一个随机索引,并在每次 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/

相关文章:

javascript - 如何获取条形图宽度(以像素为单位)

javascript - 如何使用 ng-repeat 定义表的 td colspan? (AngularJS)

javascript - 你需要 spy 来测试 Jasmine 中是否调用了一个函数吗?

arrays - N 维数组的实际使用,其中 (N>3)

javascript - AngularJS 中的抽象状态

javascript - 禁用警报消息

java - 如何在不使用存储阵列的情况下将 2D 阵列旋转 90 度?

php - 循环遍历二维 session 数组购物车php

java - 二维数组平均值 (Java)

python - 可视化高维场箭头?