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
因为二者都是用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