different between forEach and map js

The important difference between them is that map accumulates all of the results into a collection, whereas foreach returns nothing. map is usually used when you want to transform a collection of elements with a function, whereas foreach simply executes an action for each element.


二者最重要的區別:

forEach 的

Return value

undefined.


因爲二者都是用callback方法,所以,break 和continue都不可用

map或者forEach;

var new_array = arr.map(callback[, thisArg])
thisArg:Optional. Value to use as this when executing callback.

var that =this;

oky.οnclick=function(){

[1,2,3,4].forEach(function(v,k){
if(v>2){
console.log(that.i);
}
}, that);
}

如果沒有傳入that, callback中的this是指oky,現在callback的執行上下文環境是that

 





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章