leo*_*ess 5 javascript arrays ecmascript-6
我有一个长度为 n 的对象数组,我想将其扩展到长度为 n+1。为了便于使用,我想复制最后一个元素,然后更改副本的属性。
let arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];
arr.push(arr[1]); // extend by copying the last
arr[2].id += 1; // change the id of the new last
arr[2].name = 'foobar'; // change the name of the new last
console.log(arr);Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中(使用浏览器控制台,因为代码片段控制台在这里的行为有点奇怪)是我尝试过的,但出于某种原因,对复制/新最后一个元素的任何更改也适用于原始/旧最后/新第二个元素-数组中的最后一个元素。
我怎样才能正确地做到这一点,为什么我的代码的行为方式如此?
您可以推送对象的副本并省略相同的对象引用。
let arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];
arr.push({ ...arr[1] }); // extend by copying the last
arr[2].id += 1; // change the id of the new last
arr[2].name = 'foobar'; // change the name of the new last
console.log(arr);Run Code Online (Sandbox Code Playgroud)