JS中map 与 forEach 的对比

map 与 forEach 的用法:
var arr = [1,2,3,4,5]

1.相同点:用法一样

arr.map(function(v,i){
    console.log(v,i)
})

arr.forEach(function(v,i){
    console.log(i,v)
})

2.不同点:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

a. map 在对数组遍历过程,加工数组元素,最后返回一个新的数组,原数组不变;

var new_arr = arr.map(function(v,i){
return i*2
})
console.log('旧数组',arr)
console.log('新数组',new_arr)

官方示例:

var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { 
  return x.charCodeAt(0); 
});
a // [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

个人思维拓展:
(1).可以应用对 json 数组数据进行修饰(小数点截取等)

(2).可以对新数组进行翻转

var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { 
  return x.charCodeAt(0); 
}).reverse()

(3).用于数组内容格式化:

['1', '2', '3'].map( str => parseInt(str) );
['1', '2', '3'].map(Number); // [1, 2, 3]
['1', '2', '3'].map(returnInt); // [1, 2, 3]
function returnInt(ele){
    return parseInt(ele,10)
}

b. forEach 简单的遍历,不返回任何东西;

var testbb = arr.forEach(function(v,i){
console.log(i,v)
    return i*2
})
testbb // undefined
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值