Can you fake Array.isArray () with a custom object?

I am wondering if there is a way to fake Array.isArray() with a user-defined object.

From the JavaScript Templates book:

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

This object obviously fails, but is there any other way to do this? This is just curiosity, and not because I think you could ever embed .isArray() in regular client code (although it would obviously be fantastic to find out if you can!).

+8
javascript
source share
2 answers

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

The isArray function takes a single arg argument and returns a boolean true if the argument is an object whose internal property is an Array; otherwise, it returns false .

Or you go in the opposite direction: create a normal array and explicitly set each array method to undefined .

+9
source share

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

And if you want to be naughty

 Array.isArray.toString = function () { return 'function () { [native code] }'; }; 
+10
source share

All Articles