【问题标题】:How to duplicate the last element of an array? [duplicate]如何复制数组的最后一个元素? [复制]
【发布时间】:2019-12-06 20:30:45
【问题描述】:

我有一个长度为 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);

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

我怎样才能正确地做到这一点,为什么我的代码会这样?

【问题讨论】:

  • arr.push(arr[1]); arr[1] 的相同引用传递给推送的元素 arr[2]。这不是复制arr[1]
  • @MiXT4PE, arr.push({ ...arr[1] });
  • 推送一个空对象 - arr.push({}) - 并更新它不是更容易吗?
  • 这真的是复制品吗?答案似乎不同..
  • @MiXT4PE 这在技术上是重复的,因为这里真正的问题是复制对象。我个人知道问题是“如何复制数组的最后一个元素”,但实际上,这里真正的问题是您 没有 克隆元素,因此,问题变成了“如何正确克隆一个对象”,已经有很多答案了。问题清楚地暴露了,你的努力实际上是可见的,这很好。

标签: javascript arrays ecmascript-6


【解决方案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);

【讨论】:

  • 谢谢!我会尽快接受。也许还可以解释...arr[1] 如何创建副本
  • ...arr[1],将现有对象中的所有键和值传播到一个新对象中,这就是为什么您不再有引用问题的原因,很好的答案:)
  • 另外,使用扩展运算符进行克隆时请小心。克隆的深度只有 1 级。在你的情况下它很好。
【解决方案2】:

const arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];
const lastEl = Object.assign({}, arr[1]);
lastEl.id = 4;
lastEl.name = 'foo';
arr.push(lastEl);
console.log(arr);

【讨论】:

    猜你喜欢
    • 2010-09-14
    • 2020-02-04
    • 2023-04-02
    • 1970-01-01
    • 2019-02-02
    • 2016-12-07
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多