2016-01-13 62 views
0

我有一些代碼如下所示,我明白它在做什麼,但我不明白部分語法。我想知道是否有人可以向我解釋。基本上,代碼是用0到2之間的隨機整數數組填充二維數組。我沒有得到的是,爲什麼在第二個for循環後面放置「result [i] [j]」。爲什麼我不把結果[j]代替。我在網上找到了這些代碼,並知道它做了什麼,但是我再也沒有理解這種語法。硬件時間與二維數組For循環語法

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

回答

0

2D陣列具有2參考點認爲它作爲表I表示它的行和J其列,語法簡單地告訴程序要被存儲的值應該是在第i行第j個和列,如果你不提供第i個位置它不會承認行被認爲是 希望這有助於:)

+0

是啊,這是有道理的。非常感謝! :) – user4531234

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

比方說,你傳遞到函數的3 widthheight值...

buildArray(3, 3); 

你可以認爲width價值爲代表的「數列'和height值表示每列中'項目'的數量。

在第一個for循環的第一次迭代中,result有一列。由於i爲零,在這個時候,我們可以說...

result[0] = new Array(); 

該數組是空的,但隨後的第二個for循環開始發揮作用。

第二個for-loop填充新調用的數組,在本例中使用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項。等等

result中第二個括號中的值指示「height」數組中值的索引位置,它本身是由result數組的第一個括號中的索引位置指示的。

在示例結束時result將是一個數組length = 3(三個數組),每個數組包含三個隨機生成的整數。

嘗試像這樣在更換console.log() ...

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

...讓生成的隨機數的指數位的一個更好的主意。

而且你可能想挫折感:Creating a custom two-dimensional Array @ javascriptkit.com