var arr1 = [1, 2];
var arr2 = arr1;
console.log(arr1); //[1, 2]
console.log(arr2); //[1, 2]
arr1.push(6);
arr2.push(7);
console.log(arr1); //[1, 2, 6, 7]
console.log(arr2); //[1, 2, 6, 7]
由以上操作可知简单的 = 赋值都不能达到预想效果,不是新建一个和原对象(数组也是对象)完全一样的对象,而是把原对象的内存地址直接复制给了另一个对象,也就是说两个对象都是指向同一个内存地址
方法一: [].concat()
var arr1 = [1, 2];
var arr2 = [].concat(arr1);
console.log(arr1);//[1, 2]
console.log(arr2);//[1, 2]
arr1.push(6);
arr2.push(7);
console.log(arr1);//[1, 2, 6]
console.log(arr2);//[1, 2, 7]
方法二:JSON.parse(JSON.stringify())
var arr1 = [1, 2];
var arr2 = JSON.parse(JSON.stringify(arr1));
console.log(arr1); //[1, 2]
console.log(arr2); //[1, 2]
arr1.push(6);
arr2.push(7);
console.log(arr1); //[1, 2, 6]
console.log(arr2); //[1, 2, 7]
方法三:Object.assign({}, arr1);
var arr1 = { a: 0 };
var arr2 = Object.assign({}, arr1);
console.log(arr1); //{ a: 0 }
console.log(arr2); //{ a: 0 }
arr2.b = 2;
arr1.c = 3;
arr1.a = 4;
console.log(arr1); //{ a: 4, c: 3}
console.log(arr2); //{ a: 0, b: 2 }
arr2.a = 5;
console.log(arr1); //{ a: 4, c: 3}
console.log(arr2); //{ a: 5, b: 2 }
方法四 直接遍历
var array = [1, 2, 3, 4];
var copyArray = array.slice();
copyArray[0] = 100;
console.log(array); // [1, 2, 3, 4]
console.log(copyArray); // [100, 2, 3, 4]
方法五 slice() 返回一个从已有的数组中截取一部分元素返回新数组(不改变原数组)
var array = [1, 2, 3, 4];
var copyArray = array.slice();
copyArray[0] = 100;
console.log(array); // [1, 2, 3, 4]
console.log(copyArray); // [100, 2, 3, 4]
网友评论