Rotate the fake array I created into a real array in JavaScript

I know that in JavaScript sometimes the system creates a fake array, which means that it is actually an object, not an instance of the array, but still has some of the functionality of the array. For example, the argument variable that you get inside the functions is a fake array created by the system. In this case, I know what to turn it into a real array, which you can do:

var realArray = Array.prototype.slice.call(fakeArray);

But what if a fake array was not created by the system, what if fakeArray was simple:

var fakeArray = { "0": "some value", "1": "another value" };

In this case, and I tested it, using the above method will result in an empty array. What I want is to turn a fake array, as in the example I gave (created by me, not the system), into a real array. And before you tell me to just make the fake array a real array from the start, you should know that I am getting a fake array from a resource with which I do not control.

So, how do I turn a fake array not created by the system into a real array?

+5
source share
3 answers

Your example will work if your "fake array" is assigned the corresponding property .length.

This will not work in some older versions of Internet Explorer.


" "

, Object.keys...

var len = Object.keys(fakeArray).length;

Object.keys , ...

if (!Object.keys) {
    Object.keys = function(o) {
        var keys = [];
        for (var k in o)
            if (o.hasOwnProperty(k))
                keys.push(k)
        return keys;
    };
}

"", , show @Rocket.

+5

"" .

var fakeArray = { "0": "some value", "1": "another value" };
var realArray = [];

for(var i in fakeArray){
    realArray[i] = fakeArray[i];
}
+3

You can iterate over the properties of an object by clicking on the ones you want to add to the new array:

var array = [];

for (var i in fakeArray) if (fakeArray.hasOwnProperty(i)) {
    array.push(fakeArray[i]);
}
0
source

All Articles