简体   繁体   English

推向多维数组

[英]Pushing to multi-dimensional array

I'm having trouble pushing to a multi-dim array, I get the error 我在推入多维度数组时遇到问题,出现错误

_this.fieldRefs[ID].push is not a function _this.fieldRefs [ID] .push不是函数

My code is quite simple, so I thought: 我的代码很简单,所以我想:

this.fieldRefs = this.fieldRefs || []; // init `this.fieldRefs` if it doesn't exist
this.fieldRefs.push(ID); // push the `ID` e.g `0`
this.fieldRefs[ID].push(ref); // add the `ref` to `0` (ref is an ele)

The first two lines work correctly, and this.fieldRefs contains ID eg: 前两行正常工作, this.fieldRefs包含ID例如:

this.fieldRefs = [0]

But the final line is where the error occurs. 但是最后一行是发生错误的地方。 If I check this.fieldRefs[ID] I do indeed get 0 but I cannot push to 0 index 如果我检查this.fieldRefs[ID]我确实得到了0但我无法将索引推到0

What you want to do is to assign an array of refs related to an ID. 您要做的是分配一个与ID相关的引用数组。

So if ID will always be a number, instead of pushing this value to an existing array, it would be a better idea to initialize an array in the index defined by that ID. 因此,如果ID始终是一个数字,而不是将此值推送到现有数组,则最好在该ID定义的索引中初始化一个数组。 Like this: 像这样:

this.fieldRefs = this.fieldRefs || []; 
this.fieldRefs[ID] = []; 
this.fieldRefs[ID].push(ref).

What you are doing currently is different, since you are storing the values of ID on consecutive indices in your fieldRefs array, but the indices don't match the ID values. 当前的操作有所不同,因为您将ID的值存储在fieldRefs数组中的连续索引上,但是索引与ID值不匹配。

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

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