forEach 方法 Node.childNodes?

forEach method of Node.childNodes?

在为一个问题提供 concerning the .item() property of Node.childNodes 之后,我检查了 form 元素返回的 childNodes__proto__ 并找到了一个 forEach 方法。

Node.childNodesforEach 方法未记录在 NodeList, in Methods at MDN, or Interface NodeList, and does not appear to be mentioned in Iterate a NodeList using forEach method 的规范或链接到该问题的页面中;虽然它似乎在 Chromium 50 中可用。

该方法仅适用于 Chrome / Chromium 的较新版本吗?如果是,是否记录在案?

有没有关于Node.childNodesforEach()方法的文档?


document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();
  var form = e.target;
  form.childNodes.forEach(function(el) {
    if (el.tagName === "INPUT" && el.type !== "submit")
      snippet.log("name:" + el.name + ", value:" + el.value)
  });
});
<form>
  <input type="text" name="firstName" value="The first name">
  <input type="text" name="lastName" value="The last name">
  <input type="email" name="emailAddress" value="email@example.com">
  <br>
  <input type="submit" value="Submit">
</form>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

DOM4 现在将 NodeList 定义为可迭代对象:

iterable<Node>;

根据IDL draft,这意味着

An interface can be declared to be iterable by using an iterable declaration (matching Iterable) in the body of the interface.

iterable<value-type>;
iterable<key-type, value-type>;

Objects implementing an interface that is declared to be iterable support being iterated over to obtain a sequence of values.

Note: In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.

如果给出单个类型参数,则接口有一个值 iterator 并提供指定类型的值。

Is the method available only at relatively recent versions of Chrome / Chromium? If yes, is this documented?

是的,这是 DOM4 中的新功能,因此并未广泛使用。

Is there any documentation concerning the forEach() method of Node.childNodes?

请参阅 Chromium 错误跟踪器上的 Add support for [ArrayClass] and use that on NodeList

From https://bugs.webkit.org/show_bug.cgi?id=81573

http://dom.spec.whatwg.org/#interface-nodelist

DOM4 specs NodeList as having Array.prototype in its prototype chain.

Some more background for this one. [ArrayClass] allows us to do things like document.querySelectorAll('.foo').forEach etc. The patch at bugs.webkit.org has a runtime flag because it is unclear if this will still be possible to achieve.

从历史上看,这些类似数组的对象不包含数组原型中的这些方法,导致代码像 Array.prototype.forEach.call(nodeList, function() { ... })。这现在意味着在 DOM4 中有所改变。