Skip to content

Instantly share code, notes, and snippets.

@schnogz
Last active December 27, 2023 08:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schnogz/ec00de43ef83fbb927c2 to your computer and use it in GitHub Desktop.
Save schnogz/ec00de43ef83fbb927c2 to your computer and use it in GitHub Desktop.
JavaScript .isArray Implementations
// 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