Last active
December 27, 2023 08:13
-
-
Save schnogz/ec00de43ef83fbb927c2 to your computer and use it in GitHub Desktop.
JavaScript .isArray Implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Attempt #1: using typeof | |
// fails in all cases since typeof [] returns "object" | |
Array.prototype.isArray = function(obj) { | |
return (typeof obj === "array"); | |
} | |
// Attempt #2: using instanceof | |
// fails when obj = Array.prototype | |
// and when array is defined in another window or frame | |
Array.prototype.isArray = function(obj) { | |
return (obj instanceof Array); | |
} | |
// Attempt #3: using object prototype.toString | |
// this works and is the actual ECMAScript 5.1 implementation | |
Array.prototype.isArray = function(obj) { | |
return Object.prototype.toString.call(obj) == "[object Array]"; | |
} | |
// Attempt #4: using duck typing | |
// this works for the most part but is easily fooled | |
Array.prototype.isArray = function(obj) { | |
if (typeof arg === 'object' && | |
('join' in arg && typeof arg.join === 'function') && | |
('length' in arg && typeof arg.length === 'number')) { | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment