jQuery处理数组不正确:length=0错误



我不知道这是我对jQuery的一点了解,还是只是一个bug,但情况如下。我有一小段JSON代码


{
"planes":[
{
"id":1,
"name":"Boeing 767-300",
"height":54.9 ,
"wingspan":47.6, 
"vel": 851,
"vel max":913,
"plane width":283.3,
"weight":86070, 
"full weight":158760, 
"passengers":{
"1 class":350,
"2 class":269,
"3 class":218
},
"fuel tank":90.625,
"engine":"2 turbofan General Electric CF6-80C2"
},
{
"id":2,
"name":"Boeing 737-800",
"height":33.4 ,
"wingspan":35.8, 
"vel": 840,
"vel max":945,
"plane width":105.44,
"weight":32704, 
"full weight":56472, 
"passengers":{
"1 class":189
},
"fuel tank":90.625,
"engine":"2 turbofan CFM56-3C1"
}
]
}

然后我用jQuery的getJSON得到了它,没有任何缺陷。然后我想要两个独立的数组:一个保存键,另一个保存值,Object.keysObject.values也没有问题。通过将结果记录在一个字符串中,一切都很好。直到我尝试使用键作为索引,使用值作为数据来构造关联数组。通过记录结果,我得到了一个值为"0"的额外"长度"索引。这是我的jQuery代码


var arr=[];
$.getJSON("js/jsondata.json", function(data){
var keys= Object.keys(data.planes[0]);
var values= Object.values(data.planes[0]);
//im only testing on the first object, for now
$.each(keys, function(i){
//creating the associative index and assigning the value
arr[keys[i]]= values[i];
console.log("Key: "+ keys[i]+", Value: "+values[i]);
//this logs the exact values and indexes
});
console.log(arr);
//this logs an extra "length" 0
});

您真正想要使用的是key-value对象,而不是数组。所以你至少可以选择:

实际上,数组是对象,您可以附加/添加新的属性,但是,这类对象具有预定义的原型和属性。其中一个性质是length。因此,您将获得一个"意外"属性length

  1. 将此var arr = [];更改为此var arr = {};
  2. 将此var arr = [];更改为此var arr = Object.create(null);

向对象数组添加属性

let arr = [2];
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // 1 cause length is part of Array type.

key-value对象添加属性

let arr = {}; // Object.create(null);
arr['myKey'] = 'EleFromStack';
console.log(arr.myKey);
console.log(arr.length); // undefined cause length is not part of the Object type.

最大的问题是JavaScript中没有关联数组这样的野兽。所有数组都必须具有编号索引。使用对象处理所需的关联方式。

因此,您可以将平面数组中的第一个平面分配给一个变量,并保留原始关联,而不是迭代它

您试图以这种方式将对象分解并重新组装为数组,这有什么特殊的原因吗?

相关内容

最新更新