先說(shuō)結(jié)論:當(dāng)數(shù)組元素是基本數(shù)據(jù)類型時(shí),map()方法不會(huì)改變?cè)瓟?shù)組;當(dāng)數(shù)組元素是引用類型時(shí),map()方法會(huì)改變?cè)瓟?shù)組。
定義和用法
map() 方法返回一個(gè)新數(shù)組,數(shù)組中的元素為原始數(shù)組元素調(diào)用函數(shù)處理后的值。
map() 方法按照原始數(shù)組元素順序依次處理元素。
注意: map() 不會(huì)對(duì)空數(shù)組進(jìn)行檢測(cè)。
注意: map() 不會(huì)改變?cè)紨?shù)組。
發(fā)現(xiàn)問(wèn)題
數(shù)組元素為基本數(shù)據(jù)類型時(shí)使用map()方法:
// 基本數(shù)據(jù)類型
const arr = [1, 2, 3]
const newArr = arr.map(item => item * 2)
console.log(arr) // [ 1, 2, 3 ]
console.log(newArr) // [ 2, 4, 6 ]
數(shù)組元素為引用數(shù)據(jù)類型時(shí)使用map()方法:
// 基本數(shù)據(jù)類型
const arr = [{
name: 'a'
}, {
name: 'b'
}, {
name: 'c'
}]
const newArr = arr.map(item => {
item.age = 10
return item
})
console.log(arr)
// [ { name: 'a', age: 10 }, { name: 'b', age: 10 }, { name: 'c', age: 10 } ]
console.log(newArr)
// [ { name: 'a', age: 10 }, { name: 'b', age: 10 }, { name: 'c', age: 10 } ]
可以看到數(shù)組元素為對(duì)象時(shí)使用map()方法后原數(shù)組也跟著變化了,原因是因?yàn)?strong>基本類型傳值是復(fù)制,引用類型傳值是引用
解決方法
比如數(shù)組元素為對(duì)象時(shí)map()方法中處理函數(shù)就返回一個(gè)新的對(duì)象:
const arr = [{
name: 'a'
}, {
name: 'b'
}, {
name: 'c'
}]
const newArr = arr.map(item => {
return {
...item,
age: 10
}
})
console.log(arr)
// [ { name: 'a' }, { name: 'b' }, { name: 'c' } ]
console.log(newArr)
// [ { name: 'a', age: 10 }, { name: 'b', age: 10 }, { name: 'c', age: 10 } ]