簡體   English   中英

推向多維數組

[英]Pushing to multi-dimensional array

我在推入多維度數組時遇到問題,出現錯誤

_this.fieldRefs [ID] .push不是函數

我的代碼很簡單,所以我想:

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)

前兩行正常工作, this.fieldRefs包含ID例如:

this.fieldRefs = [0]

但是最后一行是發生錯誤的地方。 如果我檢查this.fieldRefs[ID]我確實得到了0但我無法將索引推到0

您要做的是分配一個與ID相關的引用數組。

因此,如果ID始終是一個數字,而不是將此值推送到現有數組,則最好在該ID定義的索引中初始化一個數組。 像這樣:

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

當前的操作有所不同,因為您將ID的值存儲在fieldRefs數組中的連續索引上,但是索引與ID值不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM