What is going on here?
var x = {length:3, '0':'foo', '1':'bar','2':'f', splice:function(){}}
This actually creates an array:
["foo", "bar", "f"]
Where is the documentation for this structure syntax?
It’s also smart:
changing to: (notice 0 , 1 , 3)
var x = {length:3, '0':'foo', '1':'bar','3':'f', splice:function(){}}
will mess up the array and it will be:
["foo", "bar", undefined × 1]
Also, removing the splice function:
var x = {length:3, '0':'foo', '1':'bar','2':'f'}
yields: (regular object)
Object
0: "foo"
1: "bar"
2: "f"
length: 3
__proto__: Object
So I have two questions:
-
What is this structure?
length , element , splice -
Say I have
['john','paul','yoko']and now I want to create the objectvar x = {length:3, '0':'john', '1':'paul','2':'yoko', splice:function(){}}How would I do this?
An array is nothing else than an object, with some methods implemented, when you make
console.log(x), your console recognizes the model of an array, and display it like it has been configured to do so.Arrayis an object available by default in Javascript, and it is handled a bit differently than other objects by the browser (see @MathiasSchwarz comment), but in its structure, it is an object like the others (there’s methods that you can call, and you can add indexes. Though, you don’t usually use string indexes like in “normal” objects, because it’s not aimed to be used like that).But your object is not really an
Array, you can do whatever you want without referring to what is displayed in the console.