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/ja/web/api/nodelist/foreach/index.html | 123 +++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 files/ja/web/api/nodelist/foreach/index.html (limited to 'files/ja/web/api/nodelist/foreach') diff --git a/files/ja/web/api/nodelist/foreach/index.html b/files/ja/web/api/nodelist/foreach/index.html new file mode 100644 index 0000000000..887d385f47 --- /dev/null +++ b/files/ja/web/api/nodelist/foreach/index.html @@ -0,0 +1,123 @@ +--- +title: NodeList.prototype.forEach() +slug: Web/API/NodeList/forEach +tags: + - DOM + - Iterable + - Method + - NodeList + - Reference + - Web +translation_of: Web/API/NodeList/forEach +--- +

{{APIRef("DOM")}}

+ +

{{domxref("NodeList")}} インターフェースにおける forEach() メソッドは、引数に渡されたコールバックをリストの各値のペアに対して 1 度ずつ挿入順で呼び出します。

+ +

構文

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

パラメーター

+ +
+
callback
+
+

someNodeList の各要素に対して実行する関数で、3 つの引数を受け付けます。

+ +
+
currentValue
+
現在 someNodeList で処理されている要素です。
+
currentIndex {{Optional_inline}}
+
現在 someNodeList で処理されている currentValue の添字です。
+
listObj {{Optional_inline}}
+
forEach() を適用しようとしている someNodeList です。
+
+
+
thisArg {{Optional_inline}}
+
callback 内で this として使う値です。
+
+ +

戻り値

+ +

{{jsxref('undefined')}}.

+ +

+ +
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
+ +

ポリフィル

+ +

以下の {{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)

+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName("WebIDL", "#es-forEach", "forEach")}}{{Spec2("WebIDL")}}iterable 宣言でforEach を定義。
+ +

ブラウザーの互換性

+ + + +

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

+ +

関連情報

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