1

我有这个功能:

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,result[lootType][d] === undefined仅当“d”变为2或3时(其他时候“d”=== 0或1)。

我假设如果我将值分配给数组的未定义字段,它将被这个值填充。

我已经找到解决方案 -

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

工作正常,它返回正确的二维数组,但我想知道这些数组是怎么回事。

4

1 回答 1

0

我不得不说问题是results您作为参数传递的对象。如果它没有在这些索引上创建足够的数组,那么这些位置将是未定义的,并且会在您尝试分配给它们时抛出。您修改后的版本会起作用,因为它复制了对已初始化数组的引用。

于 2012-09-15T12:50:47.780 回答