Created
February 10, 2016 17:59
-
-
Save glafarge/64cdfef69cb5d8afc1ba to your computer and use it in GitHub Desktop.
Check if variable is Array
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
/** | |
* Check whether an object is Array or not | |
* @type Boolean | |
* @param {object} subject is the variable that is | |
* tested for Array identity check | |
*/ | |
var isArray = (function () { | |
// Use compiler's own isArray when available | |
if (Array.isArray) { | |
return Array.isArray; | |
} | |
// Retain references to variables for performance | |
// optimization | |
var objectToStringFn = Object.prototype.toString, | |
arrayToStringResult = objectToStringFn.call([]); | |
return function (subject) { | |
return objectToStringFn.call(subject) === arrayToStringResult; | |
}; | |
}()); | |
console.log( isArray(123) ); // false | |
console.log( isArray(true) ); // false | |
console.log( isArray("my little string") ); // false | |
var obj = { | |
items: [ | |
{id:1, name:'alpha'}, | |
{id:2, name:'beta'}, | |
{id:3, name:'gamma'}, | |
] | |
}; | |
console.log( isArray(obj) ); // false | |
var arr = ["Saab", "Volvo", "BMW"]; | |
console.log( isArray(arr) ); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment