Pergunta

To my surprise, this code actually works in node.js:

var arr = new Array();
// also works: var arr = [];
arr[0] = 123;
arr['abc'] = 456;
arr; // node.js: [ 123, abc: 456 ], chrome: [123]

I've always thought that an array stores its objects in order, only accessible by an integer key, like a std::vector in C++. However, here it's acting like a map or an object. Adding to the confusion, the same code works as expected in chrome, returning an array with a single entry, 123. I thought node.js and chrome javascript use the same internal engine, V8. What's going on here?

Foi útil?

Solução

Javascript allows you to extend objects on the fly, and as an Array is an object you can do so.

What you are doing there is adding a new property to your array called abc and assigning it the value 456.

So you could say every object in Javascript can be used as a hashmap somehow.

EDIT

It seems that Chrome filters the non-numeric properties of the Array object at dumping whilst Node dumps every user-defined property. In my opinion Node's way is better since the alpha-numeric property is available in a for in statement:

var a = [1];
a['abc'] = 2;
for (var i in a) {
    console.log(i);
}
// Prints:
// 0
// abc

Outras dicas

The answers are right, the behaviour is maybe more understandable, if you try to display length of the array.

var ar = []
ar[0] = 42
console.log(ar.length) // 1

ar[12] = 21
console.log(ar.length) // 13

ar['ab'] = 1
console.log(ar.length) // 13 (separate property, not in array)

ar[ar.length] = 33
console.log(ar.length) // 14

ar.push(55)
console.log(ar.length) // 15

console.log(ar) // display all items specified above
//[ 42, , , , , , , , , , , , 21, 33, 55, ab: 1 ]
// which in fact really is:
// [ 42, , , , , , , , , , , , 21, 33, 55] as array and 
// special property of array object - 'ab':1

While chrome doesn't show 456 in the console when you just enter arr, arr.abc will still be 456.

It just doesn't show it in the console unless you explicitly access the variable, or console.log(arr), which logs: [123, abc: 456].

Basically, this is just a cosmetic issue. Node.js does show key/value properties on array objects, when you just enter the variable in the console, while chrome only shows "normal" array entries, even though both arrays actually have the same contents.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top