循环语法的2-D数组的困难时间

Hard Time with 2-D Array For-Loop Syntax

本文关键字:时间 2-D 语法 循环 数组      更新时间:2023-09-26

下面显示了一些代码,我理解它在做什么,但我不理解其中的部分语法。我想知道是否有人能向我解释一下。基本上,代码是用0到2之间的随机整数数组填充2D数组。我不明白的是,为什么我把"result[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;
}

假设您将widthheight值3…传递到函数中

buildArray(3, 3);

您可以认为width值表示"列"的数量,height值表示每列中"项目"的数量。

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

result[0] = new Array();

数组为空,但随后第二个for循环开始发挥作用。

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

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

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

因此

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

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

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

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

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

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

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

此外,您可能还想看看:创建一个自定义的二维数组@javascriptkit.com

2d数组有2个引用点,将其视为表i代表其行,J代表其列,语法简单地"告诉"程序要存储的值应该在第i行和第J列,如果不提供第i个位置,它将无法识别要考虑的行希望这有帮助:)

让我们调试它:)

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;
}

您的疑问:

为什么我把result[i][j]放在下面的第二个for循环之后。为什么我不直接放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;
}