js循环nodelist,javascript forEach在nodelist上

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.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值