简体   繁体   English

二维数组中突然“未定义”

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

I have the function: 我有功能:

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;
}

First it parses this: 首先它解析:

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

And then others lootType becomes one of these: 然后其他的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]]
};

So, trouble is in this strings: 因此,麻烦在于:

 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 

According to console.log, result[lootType][d] === undefined only when "d" becomes 2 or 3(other times "d" === 0 or 1). 根据console.log,仅当“ d”变为2或3时(否则“ d” === 0或1), result[lootType][d] === undefined

I was assuming that if I will assign value to the undefined field of array, it will be filled with this value. 我以为如果我将值分配给数组的未定义字段,它将被该值填充。

I already find solution - 我已经找到解决方案-

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

works fine, it returns proper two-dimensional array, but I want to know what is the deal with those arrays. 工作正常,它返回适当的二维数组,但我想知道这些数组的处理方式。

I'd have to say the problem is the results object that you're passing as an argument. 我不得不说问题是您作为参数传递的results对象。 If it doesn't have enough arrays created on those indexes, then those locations will be undefined and will throw up when you try to assign to them. 如果在这些索引上没有创建足够的数组,则这些位置将是未定义的,并且在您尝试分配给它们时会抛出。 Your amended version would work because it copies a reference to an already initialized array. 修改后的版本将起作用,因为它会将引用复制到已初始化的数组。

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

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