原文: http://www.webhek.com/javascript-foreach-calljavascript
document.querySelectorAll()
返回的並非咱們想固然的數組,而是 NodeList
,對 NodeList
,它裏面沒有 .forEach
方法,咱們使用了這樣的方法進行循環:php
var divs = document.querySelectorAll('div'); [].forEach.call(divs, function(div) { // do whatever div.style.color = "red"; });
初次看到 [].forEach.call()
這樣的代碼,我以爲這種寫法頗有趣,爲何要這樣寫?爲何要用空數值引伸出的方法?因而研究了一下。java
[]
就是個數組,並且是用不到的空數組。用來就是爲了訪問它的數組相關方法,好比 .forEach
。這是一種簡寫,完整的寫法應該是這樣:web
Array.prototype.forEach.call(...);
很顯然,簡寫更方便。數組
至於 forEach
方法,它能夠接受一個函數參數:函數
[1,2,3].forEach(function (num) { console.log(num); });
上面的這句代碼中,咱們能夠訪問 this
對象,也就是 [1,2,3]
,能夠看出,這個 this
是個數組。ui
最後, .call
是一個prototype,JavaScript函數內置的。 .call
使用它的第一個參數替換掉上面說的這個 this
,也就是你要傳人的數組,其它的參數就跟 forEach
方法的參數同樣了。this
[1, 2, 3].forEach.call(["a", "b", "c"], function (item, i, arr) { console.log(i + ": " + item); }); // 0: "a" // 1: "b" // 2: "c"
所以, [].forEach.call()
是一種快速的方法訪問 forEach
,並將空數組的 this
換成想要遍歷的list。spa