如题,今天笔者在使用map函数时发现很多教程文档并没有说清楚其中的一个细节,比如对于map函数的说明,菜鸟教程提到
注意: map() 不会改变原始数组。
比如以下例子:
var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(array1);
// expected output: Array [1, 4, 9, 16]
console.log(map1);
// expected output: Array [2, 8, 18, 32]
但是这是针对数组中的元素都是基本类型时才是这样的情况,而如果数组中的元素包括了对象类型的话:
let arr = [
{a: 1, b: 2},
{a: 3, b: 4},
]
arr.map((item, index) => {
if (index === 0) {
item.a = item.a + 1
item.c = true
} else {
item.c = false
}
return item
})
console.log('ss', arr)
我们发现输出结果是这样的
下面这个例子更加明显:
let arr2 = [3, 9, {attr: 2}]
arr2.map((item, index) => {
if (index === 0) {
item = item + 1
}
if (index === 2 ) {
item.attr = false
}
return item
})
console.log('arr2', arr2)
输出结果:
从打印结果发现arr2调用map函数处理自身元素属性时,作为基本类型的一个元素值经过回调处理后没有发生改变,而第三个元素因为时对象类型,当被赋值处理后影响到了arr2本身。
因此,在我们总结map方法的作用时,这么说更加准确:
map
不修改调用它的原数组本身(当然可以在callback
执行时改变原数组)
另外关于map的使用场景(上面的例子为了演示方便没有把map处理返回后的结果赋值给一个新数组,实际上要用map最好是要有新的数组来接收返回值,filter之类的函数同理,否则用forEach会更合适些):
因为map生成一个新数组,当你不打算使用返回的新数组却使用map是违背设计初衷的,请用forEach或者for-of替代。你不该使用map: A)你不打算使用返回的新数组,或/且 B) 你没有从回调函数中返回值。
参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map