JS 数组和对象的深拷贝操作示例
程序员文章站
2022-09-06 23:46:58
本文实例讲述了js 数组和对象的深拷贝操作。分享给大家供大家参考,具体如下:一.数组的深拷贝let arr = [ undefined, function(){ console.log(123);...
本文实例讲述了js 数组和对象的深拷贝操作。分享给大家供大家参考,具体如下:
一.数组的深拷贝
let arr = [ undefined, function(){ console.log(123); }, true, null, { name:"123", age:23 } ]; // arr作为拷贝对象
1. array.from()
array.from()能将一个类数组转化成一个真正的数组,因此它返回的是一个新数组。
let arr1 = array.from(arr); arr[0] = 2; console.log(arr1); // [ undefined, [function], true, null, { name: '123', age: 23 } ]
2. object.assign()
let arr1 = object.assign([], arr) arr[0] = 2; console.log(arr1); // [ undefined, [function], true, null, { name: '123', age: 23 } ]
此方法也可用作对象的深拷贝
3. slice()
let arr1 = arr.slice(0); arr[0] = 2; console.log(arr1); // [ undefined, [function], true, null, { name: '123', age: 23 } ]
4. concat()
let arr1 = arr.concat(); arr[0] = 2; console.log(arr1); // [ undefined, [function], true, null, { name: '123', age: 23 } ]
5. 扩展运算符深拷贝
// let [...arr1] = arr; // 这两种都可以 let arr1 = [...arr]; arr[0] = 2; console.log(arr1); // [ undefined, [function], true, null, { name: '123', age: 23 } ]
此方法也可用作对象的深拷贝
二.对象的深拷贝
let obj = { name: "a", age: 20, sex: false, user: { a: 20, n: "b" }, f: function(){ return 1; }, u: undefined, n: null }
用扩展运算符和object.assign()方法可以深拷贝对象
let obj1 = object.assign({}, obj) obj[age] = 2; console.log(obj1); // let obj = { name: "a", age: 20, sex: false,user: {a: 20,n: "b},f: function(){return 1;},u: undefined,n: null}
感兴趣的朋友可以使用在线html/css/javascript代码运行工具:http://tools.jb51.net/code/htmljsrun测试上述代码运行效果。