简体   繁体   English

Array.push() 仅针对 object 的特定索引?

[英]Array.push() only to specific index of an object?

I'm setting up an object with year objects, month arrays, and days that are arrays of post objects.我正在设置一个 object,其中包含年份对象、月份 arrays 和 arrays 的发布对象。 When I try to push data to postData[year][month][date] , it pushes to all the date arrays in month .当我尝试将数据推送到postData[year][month][date]时,它推送到month中的所有日期 arrays。

let postData = {}

const addPosts = (year, month, newPosts) => {
  postData[year] = postData[year] || {}
  postData[year][month] = postData[year][month] || Array(30).fill([])
  postData[year][month][0].push('post')

  return postData
}

Outputs:输出:

{
  "2020": {
    "4": [
      [
        "post"
      ],
      [
        "post"
      ],
      [
        "post"
      ],
      ...
    ]
  }
}

Is there something about.push() I'm not understanding or is there a limit to the number of indexes you can.push() into?关于 .push() 有什么我不理解的吗,或者你 can.push() 进入的索引数量是否有限制?

This issue happens because you have assigned the same empty array [] as a reference to all of them like Array(30).fill([]) .发生此问题是因为您分配了相同的空数组[]作为对所有数组的引用,例如Array(30).fill([]) So, when you modify any one of them, it also updates each one of them like:因此,当您修改其中任何一个时,它也会更新其中的每一个,例如:

 const arr = Array(2).fill([]) arr[0].push('post') console.log(arr) //=> [["post"], ["post"]]

In this demo, you can't see this properly but if you open chrome console then you can see the actual result.在此演示中,您无法正确看到这一点,但如果您打开 chrome 控制台,那么您可以看到实际结果。

To fix this issue you can simply use .map() method and assign a new array [] to each item in the main array like:要解决此问题,您可以简单地使用.map()方法并将新数组[]分配给主数组中的每个项目,例如:

 const arr = Array(2).fill().map(a => []); arr[0].push('post') console.log(arr) //=> [["post"], []]

For reasons that I cannot explain, the answer was to forego push() , and instead set the value of that index to a new array:由于我无法解释的原因,答案是放弃push() ,而是将该索引的值设置为一个新数组:

let postData = {}

const addPosts = (year, month, newPosts) => {
  postData[year] = postData[year] || {}
  postData[year][month] = postData[year][month] || Array(30).fill([])
  postData[year][month][0] = [...postData[year][month][0], 'post']

  return postData
}

I'm going to leave this up for anyone in the future Googling for strange Array push behaviors in React, js.push() not working我打算把这个留给以后的任何人谷歌搜索React 中奇怪的数组推送行为,js.push() 不工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM