本文實例講述了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中文網其他相關文章!