簡體   English   中英

二維數組中突然“未定義”

[英]Suddenly “undefined” in the two-dimensional array

我有功能:

function composeLootTables(lootType, result) {
    for (var d in lootType.items) {
        if (result[lootType.title] === undefined) {
            result[lootType.title] = [[0],[0]];
        }
        result[lootType.title][d][0] = lootType.items[d][0];
        result[lootType.title][d][1] = lootType.items[d][1];
        composeLootTables(lootType.items[d][0], result);
    }
    return result;
}

首先它解析:

residential : {
    title: "residential",
    items:[
        [generic, 0.7],
        [military, 0.7],
        [hospital, 0.7],
        [Colt1911, 0.5]
   ]
},

然后其他的lootType成為其中之一:

var Colt1911 = {
    title: "Colt 1911"
};
var generic = {
     title: "Generic",
     items: [[tin_can, 0.2],[jelly_bean, 0.3]]
};
var military = {
    title: "Military",
    items: [[bfg, 0.2],[akm, 0.3]]
};
var hospital = {
    title: "Hospital",
    items: [[condoms, 0.2],[zelyonka, 0.3]]
};

因此,麻煩在於:

 result[lootType.title][d][0] = lootType.items[d][0];
 result[lootType.title][d][1] = lootType.items[d][1];

Uncaught TypeError: Cannot set property '0' of undefined 

根據console.log,僅當“ d”變為2或3時(否則“ d” === 0或1), result[lootType][d] === undefined

我以為如果我將值分配給數組的未定義字段,它將被該值填充。

我已經找到解決方案-

result[lootType.title][d] = lootType.items[d];

工作正常,它返回適當的二維數組,但我想知道這些數組的處理方式。

我不得不說問題是您作為參數傳遞的results對象。 如果在這些索引上沒有創建足夠的數組,則這些位置將是未定義的,並且在您嘗試分配給它們時會拋出。 修改后的版本將起作用,因為它會將引用復制到已初始化的數組。

暫無
暫無

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

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