forEach()
方法在
NodeList
interface calls the callback given in parameter once for each value pair in the list, in insertion order.
someNodeList.forEach(callback[, thisArg]);
callback
A function to execute on each element of
someNodeList
. It accepts 3 parameters:
currentValue
someNodeList
.
currentIndex
可选
currentValue
being processed in
someNodeList
.
listObj
可选
someNodeList
that
forEach()
is being applied to.
thisArg
可选
this
when executing
callback
.
let node = document.createElement("div");
let kid1 = document.createElement("p");
let kid2 = document.createTextNode("hey");
let kid3 = document.createElement("span");
node.appendChild(kid1);
node.appendChild(kid2);
node.appendChild(kid3);
let list = node.childNodes;
list.forEach(
function(currentValue, currentIndex, listObj) {
console.log(currentValue + ', ' + currentIndex + ', ' + this);
},
'myThisArg'
);
The above code results in the following:
[object HTMLParagraphElement], 0, myThisArg [object Text], 1, myThisArg [object HTMLSpanElement], 2, myThisArg
This polyfill adds compatibility to all Browsers supporting ES5 :
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function (callback, thisArg) {
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
OR
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
The above behavior is how many browsers actually implement
NodeList.prototype.forEach()
(Chrome, for example).
| 规范 | 状态 | 注释 |
|---|---|---|
|
Web IDL
The definition of 'forEach' in that specification. |
候选推荐 |
定义
forEach
on
iterable
declarations
|
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
forEach
|
Chrome 51 | Edge 16 | Firefox 50 | IE No | Opera 38 | Safari 10 | WebView Android 51 | Chrome Android 51 | Firefox Android 50 | Opera Android 41 | Safari iOS 10 | Samsung Internet Android 5.0 |
完整支持
不支持
NodeList
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument