admin管理员组文章数量:1321439
To loop over the results of querySelectorAll
in JavaScript, is one of the following more preferable than the other?
[].forEach.call(document.querySelectorAll('div'){
// do something
})
[].map.call(document.querySelectorAll('div'){
// do something
})
Essentially, I'm wondering if these each achieve the same result of providing access to each dom element returned from querySelectorAll
. If so, what are reasons one might want to use one over the other?
To loop over the results of querySelectorAll
in JavaScript, is one of the following more preferable than the other?
[].forEach.call(document.querySelectorAll('div'){
// do something
})
[].map.call(document.querySelectorAll('div'){
// do something
})
Essentially, I'm wondering if these each achieve the same result of providing access to each dom element returned from querySelectorAll
. If so, what are reasons one might want to use one over the other?
3 Answers
Reset to default 7forEach operates on the original array elements. (If you want just iterate over all element you should use forEach)
map is running through your array, applying a function to each element, and emitting the result as a new array. (if you want to apply some changes to each element you should use map)
There is a subtle difference in which elements will be looped over between map
and forEach
. If the element in the array is undefined
, it will not be invoked in map
, but it will be invoked on forEach
.
Obviously this distinction does not apply in the case of querySelectorAll
, which will never return undefined
in its results.
So the only difference between them is that of what the function returns. forEach
has no return value. map
executes a function on each member of the array and returns the results. So, for instance, you could do this:
var values = [].map.call(document.querySelectorAll('input'), function(el) {
return el.value;
});
This will return an array containing the value
of every element selected by querySelectorAll('input')
.
So you should use map
when that's what you want; otherwise, use forEach
.
NB that Array.prototype.every
and Array.prototype.some
also exist; there may be times when they would be more appropriate.
forEach - only iterates the array elements.
map - iterates the array elements and returns a new array. for example..
var temp = [].map.call(document.querySelectorAll('div'), function(e){
return e.id;
// do something
})
temp is new array having id of all div elements;
本文标签: javascriptarrayforEachcall vs arraymapcallStack Overflow
版权声明:本文标题:javascript - array.forEach.call vs array.map.call - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742100550a2420780.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论