作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不知道这是否是我对 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.keys
和 Object.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
。
var arr = [];
更改为 var arr = {};
。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/
我正在编写一个 native iOS 7 应用程序,需要从 JSON api(由我控制)检索数据。 JSON 输出示例如下: { "id" : "544", "name" : "1900 Green
我是一名优秀的程序员,十分优秀!