如何复制数组的最后一个元素?

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)

在上面的代码片段中(使用浏览器控制台,因为代码片段控制台在这里的行为有点奇怪)是我尝试过的,但出于某种原因,对复制/新最后一个元素的任何更改也适用于原始/旧最后/新第二个元素-数组中的最后一个元素。

我怎样才能正确地做到这一点,为什么我的代码的行为方式如此?

Nin*_*olz 4

您可以推送对象的副本并省略相同的对象引用。

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)

  • `...arr[1]`,将现有对象中的所有键和值传播到一个新对象中,这就是为什么您不再遇到引用问题的原因,很好的答案:) (2认同)
  • 使用扩展运算符进行克隆时也请小心。克隆仅深入 1 层。在你的情况下没问题。 (2认同)