js中map()方法是否改變?cè)瓟?shù)組

先說(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 } ]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容