简体   繁体   English

Object,Object和[1:Object,2:Object]之间有什么区别?

[英]What is the difference between Object, Object and [1: Object, 2: Object]?

I just stumbled upon this while deleting an object in an array. 我在删除数组中的对象时偶然发现了这一点。

Here is the code: 这是代码:

friends = [];

friends.push(
    {
        a: 'Nexus',
        b: 'Muffin'
    },
    {
        a: 'Turkey',
        b: 'MonkMyster'
    }
    )

console.log(friends);

for(i in friends){
    if(friends[i].a == 'Nexus'){
          delete friends[i];
        friends.push({
            a: 'test',
            b: 'data'
        });
    }
}

console.log(friends);

It is posted on jsfiddle as well. 它也发布在jsfiddle上

Basically, why does my first console.log of friends output: [Object, Object] 基本上,为什么我的第一个console.log friends输出: [Object, Object]

But, when deleting that object in the loop and then adding a new object to the array, it logs: 但是,当在循环中删除该对象然后向该数组添加新对象时,它会记录:

[1: Object, 2: Object]

What exactly does 1:, 2: mean (obviously to associate for each object), but I wonder why it's not there after the first logging of friends ? 1:, 2:究竟是什么意思(显然要为每个对象关联),但我想知道为什么在第一次登录friends后它不存在? Is my object notation in my friends array wrong? 我的朋友阵列中的对象符号是错误的吗? I feel like I'm creating the initial friends array wrong and the JavaScript parser is correcting me? 我觉得我正在创建最初的friends数组错误,JavaScript解析器正在纠正我?

Because you deleted the first item (without reindexing) and pushed a new one. 因为您删除了第一个项目(没有重新索引)并推送了一个新项目。

Initially, you had an array with an object at its 0th position, and another one at the 1st one. 最初,你有一个数组,其中一个对象位于第0位,另一个位于第一个位置。

After the change, you have an array with an object at the 1st position, and another one at the 2nd one. 在更改之后,您有一个数组,其中一个对象位于第一个位置,另一个位于第二个位置。

Therefore, the console just wants to show that the first entry is at the 1st position instead of at 0th one. 因此,控制台只想显示第一个条目位于第1个位置而不是第0个位置。

Each console may do this differently, for example on Firefox I get 每个控制台都可以这样做,例如在我得到的Firefox上

Array [ <1 empty slot>, Object, Object ]

The console is just a debugging tool, you can just ignore those syntaxes. 控制台只是一个调试工具,您可以忽略这些语法。 You are not doing anything wrong. 你没有做错任何事。

However, using sparse arrays may be a bit odd. 但是,使用稀疏数组可能有点奇怪。 You can consider reindexing the array instead of just deleting the property: 您可以考虑重新索引数组,而不是仅删除属性:

delete array[position];    // Just remove
array.splice(position, 1); // Remove and reindex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM