- typeof操作符
// 数值
typeof 37 === 'number';
// 字符串
typeof '' === 'string';
// 布尔值
typeof true === 'boolean';
// Symbols
typeof Symbol() === 'symbol';
// Undefined
typeof undefined === 'undefined';
// 对象
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
// 函数
typeof function() {} === 'function';
从上面的实例我们可以看出,利用typeof除了array和null判断为object外,其他的都可以正常判断。
- instanceof操作符 和 对象的constructor 属性
var arr = [1,2]
consle.log(arr instanceof Array) // true
var fun = function(){}
console.log(fun instanceof Function) // true
- 使用 Object.prototype.toString 来判断
Object.prototype.toString.call( [] ) === '[object Array]' // true
Object.prototype.toString.call( function(){} ) === '[object Function]' // true
- 使用 原型链 来完成判断
[].__proto__ === Array.prototype // true
var fun = function(){}
fun.__proto__ === Function.prototype // true
- Array.isArray()
Array.isArray([]) // true
ECMAScript5将Array.isArray()正式引入JavaScript,目的就是准确地检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的。