2014-04-18 26 views
0

我無法理解如何調用特定的數組值:
我已經註釋掉了代碼中的問題。請看一看,讓我知道爲什麼數組在該函數內產生一個結果,而在其外部產生不同的結果。要運行代碼,請使用一個網站就像repl.itJavaScript在兩種不同的上下文中調用數組值

var passengers = [ ["Thomas", "Meeks"], 
        ["Gregg", "Pollack"], 
        ["Christine", "Wong"], 
        ["Dan", "McGaw"] ]; 

var results = passengers.map(function (array) { 
    // The following prints out the first names--the entire first column. Why? 
    console.log(array[0]); 
}); 

console.log(); // Just empty space 

// Why is the following only printin the first row of passengers (which it should), but the array[0] printed out the entirety of the first column? 
console.log(passengers[0]); 
+0

因爲在第一個'console.log',你所訪問每個嵌套陣列的第一個成員。你對此有什麼期望? 'array'參數代表'乘客[0]'然後'乘客[1]''''乘客[2]'等等,所以'array [0]'是'passengers [0] [0]'然後'乘客[1] [0]'...... –

回答

2

你有一個數組的數組,所以當你打電話map這裏:

var results = passengers.map(function (array) { 
    // The following prints out the first names--the entire first column. Why? 
    console.log(array[0]); 
}); 

它通過循環外陣列。傳入函數的參數是要循環訪問的數組的元素,在這種情況下是內部數組。所以console.log(array[0])正在打印內部數組的第一個元素。

換句話說,這個代碼是大致等效於:

console.log(passengers[0][0]); 
console.log(passengers[1][0]); 
console.log(passengers[2][0]); 
console.log(passengers[3][0]); 

請注意,在這個例子中,我只穿過外陣列迭代(第一索引)。內部數組索引保持爲零。

但是後來,你必須

console.log(passengers[0]); 

它只是打印從外陣列,這是整個第一陣列內的第一個元素。

進一步閱讀

+0

爲什麼它首先在數組中循環?我從來沒有設置任何循環。我期望得到相同的結果陣列[0]和乘客[0]。 –

+0

@AdiedX它循環遍歷數組,因爲'map'的功能就是這樣。如果您想了解更多信息,我已經包含了該方法MDN文檔的鏈接。 –

+0

@AdiedX您似乎對地圖的功能感到困惑。它不會創建地圖(鍵值對)或將二維數組解析爲地圖。使用提供的函數處理數組中的每個元素後,通過數組映射循環會返回一個新數組。它是來自流行的Map-Reduce術語的地圖。 – NikhilWanpal

相關問題