Home  >  Article  >  Web Front-end  >  Methods to determine whether a variable is an array, function or object type in JavaScript_javascript skills

Methods to determine whether a variable is an array, function or object type in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:13:151028browse

Array

Array.isArray in ECMAScript5 is the native method for 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.

Copy code The code is as follows:

var isArray = Array.isArray || function(obj) {
Return Object.prototype.toString.call(obj) === '[object Array]';
}

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]'.

Copy code The code is as follows:

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'.

Copy code The code is as follows:

var isObject = function(obj) {
var type = typeof obj;
Return type === 'function' || type === 'object' && !!obj;
}

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn