使用map方法
运行下列代码:
let oldArr = [10,20,30];
// 对原始数组使用map方法并接受返回值
let newArr1 = oldArr.map((item,index,arr) => {
console.log(item,index,arr);
if(index === oldArr.length - 1)
console.log(this);
// 对数组中每个元素加一
return item + 1;
})
// 输出原数组和新数组
console.log('使用map方法后的原数组:',oldArr);
console.log('使用map方法后的返回值:',newArr1);
获得的输出结果为:
观察结果可以得出结论:①map循环数组的每一项②传入的匿名函数的参数为(当前项item,当前项索引值index,原始的数组arr)③匿名函数里的this指向window④使用map方法不会改变原始数组⑤使用map函数后返回新的数组
使用forEach方法
运行下列代码:
let oldArr = [10,20,30];
// 对原始数组使用forEach方法并接受返回值
let newArr2 = oldArr.forEach((item,index,arr) => {
console.log(item,index,arr);
if(index === oldArr.length - 1)
console.log(this);
// 对数组中每个元素加一
arr[index]++;
return item;
})
// 输出原数组和新数组
console.log('使用forEach方法后的原数组:',oldArr);
console.log('使用forEach方法后的返回值:',newArr2);
获得的输出结果为:
观察结果可以得出结论:①forEach循环数组的每一项②传入的匿名函数的参数为(当前项item,当前项索引值index,原始的数组arr)③匿名函数里的this指向window④使用forEach方法会改变原始数组⑤使用forEach方法后返回值是undefined
总结
map和forEach的共同点:
1、都循环数组的每一项
2、每次循环时匿名函数都有三个参数,依次是:当前项、当前项的索引值、原始数组
3、匿名函数里的this都指向window
map和forEach的差异点:
1、使用map方法返回新的数组,原数组不变
2、使用forEach方法没有返回值,原数组会被改变
使用场景:
map方法适用于需要返回一个新的数组的情况
forEach方法适合用于对数组进行一些操作