简体   繁体   中英

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:

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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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