使用JSON.parse(JSON.stringify(arr))进行深拷贝

/*
* 深度拷贝JSON.parse(JSON.stringify(arr))
* JSON.parse(text[, reviver]):将数据转换为 JavaScript对象
* JSON.stringify(value[, replacer[, space]]):将JavaScript对象转换为字符串
* 深度拷贝的对象如果包括正则、函数、undefined、NaN等值,会出现问题
* 请先自行测试一下,再使用,防止有坑
*/
let arrOne = [1, 2, 3, 4, 5, 6, 7]
let arrTwo = JSON.parse(JSON.stringify(arrOne))
arrTwo[0] = 8
console.log(arrOne) // [1, 2, 3, 4, 5, 6, 7]
console.log(arrTwo) // [8, 2, 3, 4, 5, 6, 7]

 

你可能感兴趣的:(Js)