From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/nodelist/foreach/index.html | 120 ++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 files/zh-cn/web/api/nodelist/foreach/index.html (limited to 'files/zh-cn/web/api/nodelist/foreach') diff --git a/files/zh-cn/web/api/nodelist/foreach/index.html b/files/zh-cn/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..29f2c575a7 --- /dev/null +++ b/files/zh-cn/web/api/nodelist/foreach/index.html @@ -0,0 +1,120 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +translation_of: Web/API/NodeList/forEach +--- +

{{APIRef("DOM")}}

+ +

{{domxref("NodeList")}}接口的 forEach() 方法按插入顺序为列表中的每个值对调用一次参数中给定的回调。

+ +

语法

+ +
someNodeList.forEach(callback[, thisArg]);
+
+ +

参数

+ +
+
callback
+
+

为 someNodeList的每一个元素执行函数。它接受以下三个参数:

+ +
+
currentValue
+
someNodeList中的当前元素。
+
currentIndex {{Optional_inline}}
+
someNodeList中的currentValue所对应的索引值。
+
listObj {{Optional_inline}}
+
someNodeList 在 forEach() 方法中所属的NodeList对象。
+
+
+
thisArg {{Optional_inline}}
+
传递 callback 的值一般用{{jsxref("this")}}值。
+
+ +

返回值

+ +

{{jsxref('undefined')}}.

+ +

Exceptions

+ +

None.

+ +

示例

+ +
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'
+);
+ +

上述代码会产生以下结果:

+ +
[object HTMLParagraphElement], 0, myThisArg
+[object Text], 1, myThisArg
+[object HTMLSpanElement], 2, myThisArg
+ +

Polyfill

+ +

{{Glossary("Polyfill","polyfill")}} 增加了对所有支持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);
+        }
+    };
+}
+ +

或者

+ +
if (window.NodeList && !NodeList.prototype.forEach) {
+   NodeList.prototype.forEach = Array.prototype.forEach;
+}
+ +

上面的代码是大部分浏览器实现的 NodeList.prototype.forEach() (例如Chrome).

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("WebIDL", "#es-forEach", "forEach")}}{{Spec2("WebIDL")}}Defines forEach on iterable declarations
+ +

Browser Compatibility

+ + + +

{{Compat("api.NodeList.forEach")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf