複製陣列
-
錯誤
let a = [1,2,3];
let b = a; //a受影響
b.push(4);
console.log(a); //[1, 2, 3, 4]
console.log(b); //[1, 2, 3, 4]
複製程式碼
-
正確複製陣列
let c = [...a]; //複製
let c = JSON.parse(JSON.stringify(a)); //複製
let c = a.concat([]); //複製
複製程式碼
複製物件
let newObj;
Object.keys(oldObj).forEach(k => (newObj[`${k}`] = res[k]));
複製程式碼