社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

jquery对数组的处理不当:length=0错误?

davide m. • 5 年前 • 295 次点击  

我不知道这是我对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.keys Object.values 。通过将结果记录在一个字符串中,一切都很好。直到我尝试构造一个关联数组,使用键作为索引,使用值作为数据。通过记录结果,我得到一个值为“0”的额外“length”索引。这是我的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
});
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46250
 
295 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Drew Knab
Reply   •   1 楼
Drew Knab    6 年前

最大的问题是javascript中没有关联数组这样的野兽。所有数组都必须有编号索引。将所需的方式与对象进行关联。

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

有没有什么特别的原因让你试着用这种方法将你的对象分解并重新组装成一个数组?

Ele
Reply   •   2 楼
Ele    6 年前

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

实际上,数组是对象,您可以附加/添加新属性,但是,此类对象具有预定义的原型和属性。这些属性之一是 length 。因为,你得到了一个“意外”的财产 长度 .

  1. 改变这个 var arr = []; 对此 var arr = {}; .
  2. 改变这个 变量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.