方法一:instanceof 判断
var arr = [1, 2, 3];
console.log(arr instanceof Array); //true
方法二:原型链方法
var arr = [1, 2, 3];
//这两句代码是一样的
console.log(arr.__proto__.constructor === Array); //true
console.log(arr.constructor === Array); //true
但是,这个有兼容问题,在IE早期版本里,__proto__是没有定义的 ~~~
方法三:通用的方法
var arr = [1, 2, 3];
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
console.log( isArray(arr) ); //true
☞ 使用 Object.prototype.toString.call() 判断数据类型
Object.prototype.toString.call([1,2])
"[object Array]"
Object.prototype.toString.call({a:18})
"[object Object]"
Object.prototype.toString.call(4)
"[object Number]"
Object.prototype.toString.call('s')
"[object String]"
Object.prototype.toString.call(true)
"[object Boolean]"
Object.prototype.toString.call(null)
"[object Null]"
Object.prototype.toString.call(undefined)
"[object Undefined]"
Object.prototype.toString.call(function(){})
"[object Function]"
Object.prototype.toString.call(/6/)
"[object RegExp]"
Object.prototype.toString.call(new Date())
"[object Date]"
Object.prototype.toString.call(new Map())
"[object Map]"
Object.prototype.toString.call(new Set())
"[object Set]"
Object.prototype.toString.call(Math)
"[object Math]"
网友评论