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 object
var 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.
Array
is 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.
x
is not an array, it's just an object. (The console shows it in array format, that's the problem of implementation of the console.)
var x = {length:3, '0':'foo', '1':'bar','2':'f', splice:function(){}};
console.log(typeof x); // object
Just use firebug as the example, take a look at the firebug's source code, and you will see why the console thought it as an array.
//...
isArray: function(obj, win)
{
if (mightBeArray(obj, win))
{
if (!obj)
return false;
// do this first to avoid security 1000 errors
else if (obj instanceof Ci.nsIDOMHistory)
return false;
// do this first to avoid exceptions
else if (obj.toString && obj.toString() === "[xpconnect wrapped native prototype]")
return false;
else if (isFinite(obj.length) && typeof obj.splice === "function")
return true;
else if (Arr.isArray(obj))
return true;
}
return false;
},
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With