Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you fake out Array.isArray() with a user-defined object?

Tags:

javascript

I'm curious about whether there is any way to fake out Array.isArray() with a user-defined object.

From the book JavaScript Patterns:

Array.isArray([]); // true

// trying to fool the check
// with an array-like object
Array.isArray({
  length: 1,
  "0": 1,
  slice: function () {}
}); // false

That object clearly fails, but is there any other way to do it? This is sheer curiosity, and not because I think that you could ever screw with .isArray() in regular client code (though it would obviously be fantastic to know if you could!).

like image 374
Josh Smith Avatar asked Dec 29 '11 18:12

Josh Smith


2 Answers

Only if you set the internal [[Class]] property to "Array", which is not possible afaik. From the specification:

The isArray function takes one argument arg, and returns the Boolean value true if the argument is an object whose class internal property is "Array"; otherwise it returns false.

Or you go the other way round: Create a normal array and explicitly set every array method to undefined.

like image 75
Felix Kling Avatar answered Nov 19 '22 20:11

Felix Kling


Array.isArray = function () { return true; }

And if you want to be naughty

Array.isArray.toString = function () { 
  return 'function () { [native code] }';
};
like image 43
Raynos Avatar answered Nov 19 '22 19:11

Raynos