ECMA6Script中的[] .forEach.call(...)的替代方法 [英] Alternative for [].forEach.call(...) in ECMA6Script

查看:128
本文介绍了ECMA6Script中的[] .forEach.call(...)的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var elements = document.querySelectorAll(' DIV'); 
[] .forEach.call(elements,function(element){
div.style.color ='green';
});

此代码可以工作,但是 []。forEach.call(... )在大型应用中不容易阅读。在ECMA6Script中,是否有一种本机方式,可以在不使用定制功能或原型的情况下更轻松地进行DOM枚举?

解决方案

ES6中的任何更多的 forEach 。您可以使用 for for loop

  for(let div of document.querySelectorAll 'div'))
div.style.color ='green';

除此之外,您可以使用 Array.from 来投射一个可迭代对象到数组,然后调用 .forEach ;但事实上,即将到来的DOM规范这是不必要的,其中 querySelectorAll 将返回一个元素集合,它继承自 Array 以ES6的方式 - 所以你可以直接调用 .forEach 方法!


I use the following code in all my applications to enumerate through DOM elements:

var elements = document.querySelectorAll('div');
[].forEach.call(elements, function(element) {
    div.style.color = 'green';
});

This code works, however [].forEach.call(...) is not easy to read in large applications. Is there a native way for easier DOM enumeration in ECMA6Script without using custom-made functions or prototypes?

解决方案

You wouldn't use forEach at all any more in ES6. You'd use a for of loop:

for (let div of document.querySelectorAll('div'))
    div.style.color = 'green';

Apart from that, you can use Array.from to cast an iterable object to an array and then invoke .forEach on that; but in fact with the upcoming DOM spec this is unnecessary where querySelectorAll will return an Elements collection that does inherit from Array in the ES6 way - so you can call the .forEach method directly on it!

这篇关于ECMA6Script中的[] .forEach.call(...)的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆