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

I just stumbled upon this by 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 hosted on jsfiddle .

Basically, why is my first console.log from friends output: [Object, Object]

But when you delete this object in a loop and add a new object to the array, it registers:

[1: Object, 2: Object]

What exactly does 1:, 2: mean (obviously, for communication for each object), but I wonder why it did not appear after the first login to friends ? Is my object notation in my friends array wrong? It seems to me that I am creating the original friends array incorrectly and the JavaScript parser corrects me?

+5
source share
1 answer

Because you deleted the first item (without reindexing) and clicked a new one.

Initially, you had an array with the object at its 0th position, and the other at the 1st.

After the change, you have an array with the object in the 1st position, and the second in the second.

Therefore, the console just wants to show that the first record is in the 1st position, and not in the 0th.

Each console can do it differently, for example in Firefox I get

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

The console is just a debugging tool, you can simply ignore these syntaxes. You are not doing anything wrong.

However, using sparse arrays can be a bit odd. You can consider re-indexing the array instead of simply deleting the property:

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

All Articles