本文实例讲述了JS 数组和对象的深拷贝操作。分享给大家供大家参考,具体如下:
let arr = [ undefined, function(){ console.log(123); }, true, null, { name:"123", age:23 } ]; // arr作为拷贝对象
Array.from()能将一个类数组转化成一个真正的数组,因此它返回的是一个新数组。
let arr1 = Array.from(arr); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
let arr1 = Object.assign([], arr) arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
此方法也可用作对象的深拷贝
let arr1 = arr.slice(0); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
let arr1 = arr.concat(); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
// 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}
相关学习推荐:javascript视频教程
以上是示例JS 数组和对象的深拷贝操作的详细内容。更多信息请关注PHP中文网其他相关文章!