2011-08-24 49 views
5

無名數組有沒有辦法使用foreach循環在一個無名數組時訪問目標對象的length屬性?訪問在Array.forEach

# I'd like to be able to do something like: 
[1, 2, 3].forEach (n, i) -> console.log n is < (arr.length - 1) 
+0

嗯,這是一個常量數組,所以你_know_長度。在這個例子中,它是3.你需要什麼? –

+3

@daniel kullmann,這個問題也適用於類似'getSomething()。for each ...'的代碼。' – arnaud576875

回答

6

Array.forEach回調採取樹參數:值,索引和陣列正被遍歷

所以,你可以這樣做:

[1, 2, 3].forEach (n, i, thearray) -> console.log n is < (thearray.length - 1) 

的Javascript:

[1, 2, 3].forEach(function(n, i, thearray) { 
    console.log(n < thearray.length - 1); 
}); 
+1

注意自我, [RTFM!](https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects /陣列/的foreach) – pdoherty926