使用Object.prototype.toString
属性
var str1 = 'abc'
var num1 = 123
var bool1 = true
var arr1 = [1, 2, 3]
var obj1 = {name: 'jack', say: function () { }}
var fun1 = function () {}
var un1 = undefined
var null1 = null
var nan1 = NaN
var log = console.log
log(Object.prototype.toString.call(str1))
log(Object.prototype.toString.call(num1))
log(Object.prototype.toString.call(bool1))
log(Object.prototype.toString.call(arr1))
log(Object.prototype.toString.call(obj1))
log(Object.prototype.toString.call(fun1))
log(Object.prototype.toString.call(un1))
log(Object.prototype.toString.call(null1))
log(Object.prototype.toString.call(nan1))
// print:
// [object String]
// [object Number]
// [object Boolean]
// [object Array]
// [object Object]
// [object Function]
// [object Undefined]
// [object Null]
// [object Number]
这个方法通用,但是繁琐。通常只需要typeof
即可解决问题。