Consider the following code:
var els = document.querySelectorAll('.myClassName');
Array.prototype.forEach.call(els, function(el) {
console.log(el.id);
});
The var els contains a nodelist, which is not an array, and forEach applies on arrays only right?
Is the above code actually a hack?
解决方案...and forEach applies on arrays only right?
Nope. Array.prototype.forEach is intentionally generic, it can be applied to any object that is array-like. From the spec:
NOTE2: The forEach function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method.
The spec clearly lays out what properties and/or methods will be used during the processing of forEach; as long as the object referenced via this during the call has those, forEach can be used on that object. That's why using forEach.call like that works: The call method on function objects (forEach is a function object) calls the function using the first argument you give call as this during the call, and passing along the following arguments as the arguments to the original function. So Array.prototype.forEach.call(x, y) calls forEach with this set to x and with the first argument set to y. forEach doesn't care about the type of this, just that it has the relevant properties and methods as described in the specification's algorithm for it.
Most of the Array.prototype methods are like that, and indeed many others on the other standard prototypes.
Side note: The NodeList returned by querySelectorAll recently became iterable on modern browsers, whcih means: 1. It works with ES2015+'s for-of, and 2. It has forEach natively now. (On modern browsers.)
本文解释了如何在NodeList上使用Array.prototype.forEach,尽管它并非数组,但通过call方法将其转换为可迭代对象。展示了forEach的通用性,并提及NodeList在现代浏览器中的变化,如ES2015+的for-of和内置的forEach支持。
338

被折叠的 条评论
为什么被折叠?



