Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array by Object (and vice versa) in JavaScript?

Tags:

javascript

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?

like image 643
Royi Namir Avatar asked Oct 29 '12 09:10

Royi Namir


2 Answers

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.

like image 169
Julien Fouilhé Avatar answered Sep 19 '22 22:09

Julien Fouilhé


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;
},
// ...
like image 26
xdazz Avatar answered Sep 19 '22 22:09

xdazz