Home >Web Front-end >JS Tutorial >Code description of how to determine whether a variable is an array, function or object in JS
Array
Array.isArray in ECMAScript5 is the native method of judging arrays, supported by IE9 and above. For compatibility reasons, in browsers that do not have this method, you can use Object.prototype.toString.call(obj) === '[object Array]' instead.
var isArray = Array.isArray || function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }
JQ does encapsulate a function jQuery.inArray(value, array) that searches for the specified value in the array and returns its index (returns -1 if not found).
valueThe value to search for. array An array through which to search.
function inArray1(needle,array,bool){ if(typeof needle=="string"||typeof needle=="number"){ for(var i in array){ if(needle===array[i]){ if(bool){ return i; } return true; } } return false; } }
Function
The simplest and best-performing method is typeof obj == 'function'. Considering the bugs in some versions of browsers, the most reliable method is Object.prototype.toString.call(obj) === '[object Function]'.
var isFunction = function(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } if(typeof /./ != 'function' && typeof Int8Array != 'object') { isFunction = function(obj) { return typeof obj == 'function'; } }
Object
In JavaScript, complex types are objects, and functions are also objects. Using typeof on the above two, you can get 'object' and 'function' respectively. In addition, null values must be excluded, because typeof null also returns 'object'.
var isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }
The above is the detailed content of Code description of how to determine whether a variable is an array, function or object in JS. For more information, please follow other related articles on the PHP Chinese website!