Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

Basically, why does my first console.log of friends output: [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? 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?

like image 668
NiCk Newman Avatar asked Jun 28 '15 21:06

NiCk Newman


1 Answers

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.

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.

Each console may do this differently, for example on Firefox I get

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
like image 50
Oriol Avatar answered Nov 14 '22 23:11

Oriol