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!).
Only if you set the internal [[Class]]
property to "Array"
, which is not possible afaik. From the specification:
The
isArray
function takes one argumentarg
, and returns the Boolean valuetrue
if the argument is an object whose class internal property is "Array"; otherwise it returnsfalse
.
Or you go the other way round: Create a normal array and explicitly set every array method to undefined
.
Array.isArray = function () { return true; }
And if you want to be naughty
Array.isArray.toString = function () {
return 'function () { [native code] }';
};
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