2-D阵列For-Loop语法的困难时期

时间:2016-01-13 05:54:41

标签: javascript arrays for-loop multidimensional-array

我有一些代码如下所示,我理解它在做什么,但我不理解部分语法。我想知道是否有人可以向我解释。基本上,代码填充了一个2D数组,其中的数组的random整数介于0和2之间。我不知道的是,为什么我要把"结果[i] [j]"在第二个for循环之后。为什么我不把结果[j]改为。我在网上找到了代码并知道它做了什么,但同样,我还没有理解这段语法。

    function buildArray(width, height){
    var result= [];

    for (var i = 0 ; i < width; i++) {

        result[i] = [];

        for (var j = 0; j < height; j++) {
            result[i][j] = Math.floor(Math.random() * 3);
            console.log(result[i][j]);
        }
    }
    return result;
}

3 个答案:

答案 0 :(得分:1)

假设您将widthheight值传递给函数...

buildArray(3, 3);

您可以将width值视为代表“列”的数量,将height值视为代表每列中“项目”的数量。

在第一个for循环的第一次迭代中,result有一列。因为此时i为零,我们可以说......

result[0] = new Array();

数组为空,但第二个for-loop开始起作用。

第二个for循环填充新调用的数组,在本例中有3个随机生成的整数。

假设第二个for循环的第一次迭代产生整数'2',第二次迭代产生'0',第三次'1'产生'0'。这意味着resutl[0]现在看起来像这样......

result[0] = [2, 0, 1];

......所以......

result[0][0] = 2;
result[0][1] = 0;
result[0][2] = 1;

然后i递增,调用位置result[1]的新数组,然后填充3个项目。等等。

result中第二个括号中的值表示'height'数组中值的索引位置,该数组本身由result数组的第一个括号中的索引位置指示。

在示例结尾result将是一个length = 3(三个数组)数组,每个数组包含三个随机生成的整数。

尝试用这样的东西替换console.log() ......

console.log('result['+i+']['+j+'] = ' + result[i][j]);

...更好地了解正在生成的随机数的索引位置。

你也可以想知道:Creating a custom two-dimensional Array @ javascriptkit.com

答案 1 :(得分:0)

2d数组有2个参考点认为它作为表i表示它的行而J表示它的列,语法只是告诉程序要存储的值应该在第i行和第j列,如果你不提供我不会识别要考虑的行的位置 希望这会有所帮助:)

答案 2 :(得分:0)

让我们调试它:)

function buildArray(width, height){
    var result= []; // declared a 1-D array

    for (var i = 0 ; i < width; i++) {

        result[i] = [];   // create another array inside the 1-D array. 
                          // result[0] = [];

          for (var j = 0; j < height; j++) {

           result[i][j] = Math.floor(Math.random() * 3); // result[0][0] = some random number
           console.log(result[i][j]);
        }

    }
    return result;
}

怀疑:

  

为什么我会在第二个for循环之后放置result[i][j]。为什么我不改为result[j]

如果你想以这种方式做,你必须修改代码。请参阅以下代码以供参考

function buildArray(width, height){
    var result= []; // declared a 1-D array

    for (var i = 0 ; i < width; i++) {

      // result[i] = [];    not required                              
        var my_array = [];   // you need to define a new array
        for (var j = 0; j < height; j++) {
            my_array[j] = Math.floor(Math.random() * 3); // fill your new array with random numbers
           //console.log(result[i][j]);   not required
        }
     result.push(my_array);  // you need to push your array into results
    }
    return result;
}