Alternative for [].forEach.call(…) in ECMA6Script

2019-08-11 01:05发布

问题:

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?

回答1:

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!



回答2:

You can use Array.from:

Array.from(elements).forEach(elem => ...)


回答3:

In ES6 you can use the spread operator:

[...document.querySelectorAll('div')].forEach(e => console.log(e))