您的位置:首页 > 其它

forEach和map的用法和区别

2017-03-06 14:23 375 查看
语法:都是用来遍历数组的每一项。

       forEach:没有返回值,对原数组不会产生影响,但是可以通过数组的索引来改变数组。

var ary = [1,2,4,7,3];
var res = ary.forEach(function (item,index,input) {
input[index] = item*10;
})
console.log(res);//-->undefined;
console.log(ary);//-->会对原来的数组产生改变;
map:map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

var ary = [12,23,24,42,1];
var res = ary.map(function (item,index,input) {
return item*10;
})
console.log(res);//-->[120,230,240,420,10];
console.log(ary);//-->[12,23,24,42,1];
 http://my.csdn.net/my/mycsdn[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: