2013-10-16 142 views
-1

我正在javascript for循環中進行測試。爲什麼javascript for循環僅顯示最後一個元素

var items = ['one','two','three'] 
for(var i=0, l=items.length; i < l; i++){ 
    console.log(i); 
    items[i]; 
} 

並且輸出如下。

0 
1 
2 
"three" 

爲什麼只有最後一個項目被打印,如果它不包含在console.log中?

編輯1:我道歉的最初的副本粘貼了。我更新了代碼。如果我將項目[i]作爲控制檯日誌的一部分進行打印,它將打印所有三個項目,但不是在外面。

+1

你不想寫'items [i]'嗎? – pbenard

+0

該代碼會給你一個參考錯誤。 – Andy

+0

什麼是'item'?哦,順便說一句,從來沒有見過這樣快的問題。雖然我沒有這樣做。 – Kaf

回答

3

你的循環本身沒有問題。你錯誤的是,考慮"three"作爲輸出。

"Three"只是這個表達式的最後一個值。

如果你會寫

var items = ['one','two','three']; 
for(var i=0; i < items.length; i++){ 
    i; // i itself just calls the variable and does nothing with it. 
     // Test it with the developer console on Google Chrome and you'll notice a 
     // different prefix before the line 
} 

就沒有輸出,因爲只有執行console.log()產生實際輸出。如果你想輸出i和位置i的數組中的值,你的代碼是:

var items = ['one','two','three']; 
for(var i=0; i < items.length; i++){ 
    console.log(i); 
    console.log(items[i]); 
} 
相關問題