更新一系列对象内的对象属性

发布于 2025-02-11 06:52:35 字数 743 浏览 1 评论 0 原文

我正在尝试使用儿童组件中的EventEmitter在数组内部的对象中更新属性。

interface productItem {
  keepOpen: boolean;
}

products$:productItem[] = Array(7).fill(
    {
      keepOpen:false
    }
  )

当用户单击按钮时,我正在使用此功能:

shouldKeepAddToBagOpen(dataFromChild: boolean, index: number): void {
    // handle callback
    this.keepAddToBagOpen = dataFromChild;
    this.products$[index].keepOpen = dataFromChild;
 
  }

但是它会影响数组中的所有项目,而不仅仅是具有给定 index 的一个功能:

我在做什么错?

I'm trying to update a property in an object inside an array using an EventEmitter in a child component.

interface productItem {
  keepOpen: boolean;
}

products$:productItem[] = Array(7).fill(
    {
      keepOpen:false
    }
  )

I'm using this function when the user clicks on the button :

shouldKeepAddToBagOpen(dataFromChild: boolean, index: number): void {
    // handle callback
    this.keepAddToBagOpen = dataFromChild;
    this.products$[index].keepOpen = dataFromChild;
 
  }

However it is affecting all the items in the array, not only the one with the given index:
enter image description here

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2025-02-18 06:52:35

当Array.fill通过一个对象时,它将复制引用并用对该对象的引用填充数组。

您可以使用以下内容:

 products = Array.from({length:7},()=> ({'keepOpen':false}))

When Array.fill gets passed an object, it will copy the reference and fill the array with references to that object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#using_fill

You could instead use something like:

 products = Array.from({length:7},()=> ({'keepOpen':false}))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文