最近看了一些html5和js方面的書,受益匪淺,因為看的東西比較多,卻都沒有怎么靜心來做整理,慢慢來吧,可能最近自己有點兒小緊張。今天跟大家分享下JavaScript的forEach方法(其實是從《HTML5程序設計》這本書里看到的一種方法)。
首先說下JavaScript的forEach的標准格式。
為數組中的每個元素執行指定操作。
array1.forEach(callbackfn[, thisArg])
對於數組中的每個元素,forEach 方法都會調用 callbackfn 函數一次(采用升序索引順序)。 不為數組中缺少的元素調用該回調函數。
除了數組對象之外,forEach 方法可由具有 length 屬性且具有已按數字編制索引的屬性名的任何對象使用。
回調函數語法
回調函數的語法如下所示:
function callbackfn(value, index, array1)
可使用最多三個參數來聲明回調函數。
回調函數的參數如下所示。
| 回調參數 |
定義 |
|---|---|
| value |
數組元素的值。 |
| index |
數組元素的數字索引。 |
| array1 |
包含該元素的數組對象。 |
修改數組對象
forEach 方法不直接修改原始數組,但回調函數可能會修改它。
好吧,上面是從微軟的http://technet.microsoft.com/zh-cn/ff679980%28v=vs.85%29頁面copy過來的,有興趣的直接去那里看就好了。也就是說一般方法的格式是:
arrayx.forEach(function(value,index,arrayy){…})
但對於NodeList要用下面的寫法。
[].forEach.call(lists,function(valule.index.arrayy){…})
Why can’t I use forEach or map on a NodeList?
NodeList are used very much like arrays and it would be tempting to use Array.prototype methods on them. This is, however, impossible.
JavaScript has an inheritance mechanism based on prototypes. Array instances inherit array methods (such as forEach or map) because their prototype chain looks like the following:
myArray --> Array.prototype --> Object.prototype --> null (the prototype chain of an object can be obtained by calling several times Object.getPrototypeOf)
forEach, map and the likes are own properties of the Array.prototype object.
Unlike arrays, NodeList prototype chain looks like the following:
myNodeList --> NodeList.prototype --> Object.prototype --> null
NodeList.prototype contains the item method, but none of the Array.prototype methods, so they cannot be used on NodeLists.
實例
- [].forEach.call(document.querySelectorAll('section[data-bucket]'), function(elem, i) {
- localStorage['bucket' + i] = elem.getAttribute('data-bucket');
- });
