JS: Use objects to obtain successful values, use arrays, and there will be values of type undefined
var bodydata = $("body").data();
// console.log(bodydata);
bodyDatas = {};/*使用了个全局变量bodyDatas*/
_.forIn(bodydata,function(value,key){
if(typeof value == "string"){
value = parseLodash(n);
}
if(value[0] == "200"){
var keyarray = key.split('_');
var key0 = keyarray[0];
var key1 = keyarray[1];
var key2 = keyarray[2];
_.forIn(_.keys(value[2]), function(v,k) {
if (!bodyDatas[key0]) {
bodyDatas[key0] = {};
}
if (!bodyDatas[key0][key1]) {
bodyDatas[key0][key1] = {};
}
if (!bodyDatas[key0][key1][key2]) {
bodyDatas[key0][key1][key2] = {};
}
if (!bodyDatas[key0][key1][key2][v]) {
bodyDatas[key0][key1][key2][v] = value[2][v];
}
});
}else{
console.log("取到数据头部:"+n[0]);
}
})
The above can obtain the correct results.
var bodydata = $("body").data();
bodyDatas = new Array();/*使用了个全局变量bodyDatas*/
_.forIn(bodydata,function(value,key){
if(typeof value == "string"){
value = parseLodash(n);
}
if(value[0] == "200"){
var keyarray = key.split('_');
var key0 = keyarray[0];
var key1 = keyarray[1];
var key2 = keyarray[2];
_.forIn(_.keys(value[2]), function(v,k) {
if (!bodyDatas[key0]) {
bodyDatas[key0] = [];
}
if (!bodyDatas[key0][key1]) {
bodyDatas[key0][key1] = [];
}
});
}else{
console.log("取到数据头部:"+n[0]);
}
})
console.log(bodyDatas["mx"]);
The above code uses an array, and there will be a value with the default type undefined
Although I solved this problem by replacing the object with the array, I still have questions in my mind. : Why when using an array, a value of type undefined is added, but this value does not exist. My loop is indeed only executed once, so maybe there is something wrong with the way I declare the array. Is there a default value in it? How should it be declared?