gpt4 book ai didi

javascript - jQuery 数组处理不当 : length= 0 bug?

转载 作者:行者123 更新时间:2023-12-03 00:51:48 25 4
gpt4 key购买 nike

我不知道这是否是我对 jQuery 的了解不够,或者这只是一个错误,但事情是这样的。我有一小段 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
});

最佳答案

您真正想要使用的是键值对象而不是数组。所以你至少有以下选择:

实际上数组是对象,您将能够附加/添加新属性,但是,这种对象具有预定义的原型(prototype)和属性。这些属性之一是长度。因此,您会得到一个“意外”属性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.

键值对象添加属性

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 - jQuery 数组处理不当 : length= 0 bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com