JavaScript forEach方法


最近看了一些html5和js方面的書,受益匪淺,因為看的東西比較多,卻都沒有怎么靜心來做整理,慢慢來吧,可能最近自己有點兒小緊張。今天跟大家分享下JavaScript的forEach方法(其實是從《HTML5程序設計》這本書里看到的一種方法)。

首先說下JavaScript的forEach的標准格式。

為數組中的每個元素執行指定操作。

array1.forEach(callbackfn[, thisArg])

參數

定義

array1

必需。 一個數組對象。

callbackfn

必需。 一個接受最多三個參數的函數。 對於數組中的每個元素,forEach 都會調用 callbackfn 函數一次。

thisArg

可選。 可在 callbackfn 函數中為其引用 this 關鍵字的對象。 如果省略 thisArg,則 undefined 將用作 this 值。

如果 callbackfn 參數不是函數對象,則將引發 TypeError 異常。

對於數組中的每個元素,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.

實例

  1. [].forEach.call(document.querySelectorAll('section[data-bucket]'), function(elem, i) { 
  2.   localStorage['bucket' + i] = elem.getAttribute('data-bucket'); 
  3. }); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM