Reputation: 78
A team handed out their project to mine, in which I saw something strange. They first declared a variable as an array:
private myvariable: Array<any> = [];
But then in the code, they were using it as an object, doing things like:
myvariable['key'] = { 'prop': 'val' }
This ends up evaluated as something strange:
[key: {...}]
Does someone know how to explain this data structure?
Upvotes: 0
Views: 53
Reputation: 28226
An Array is basically a JavaScript Object and can have properties and methods associated with it, just like a "pure" object. It being an Array will affect its behaviour when it comes to methods like .toString()
or when it is being converted by JSON.stringify()
. Its properties will not be found in the JSON representation.
You can visualise it's properties by casting (Object.assign()
-ing) it to an object like in:
var array=[1,2,3];
array.key='hello';
console.log(JSON.stringify(Object.assign({},array)));
// {"0":1,"1":2,"2":3,"key":"hello"}
This will show the array as an object (the index numbers will appear like string property names with their associated values).
Upvotes: 3