1、利用typeof
// typeof 返回的结果都是字符串形式 console.log(typeof ("a")) // string console.log(typeof (1)) // number console.log(typeof NaN) // number console.log(typeof (true)) // boolean console.log(typeof (undefined)) // undefined console.log(typeof (null)) // object console.log(typeof ({a: "1"})) // object console.log(typeof (new Object())) // object console.log(typeof ([2,4])) // object console.log(typeof (new Array())) // object console.log(function fn() {}) // ƒ fn() {}
2、万能法 Object.prototype.toString.call()
var a = Object.prototype.toString.call("a") console.log(a) // [object String] var b = Object.prototype.toString.call(1) console.log(b) // [object Number] var c = Object.prototype.toString.call(true) console.log(c) // [object Boolean] var d = Object.prototype.toString.call(undefined) console.log(d) // [object Undefined] var e = Object.prototype.toString.call(null) console.log(e) // [object Null] var f = Object.prototype.toString.call({a: "a"}) console.log(f) // [object Object] var g = Object.prototype.toString.call([]) console.log(g) // [object Array] var h = Object.prototype.toString.call(function fn() {}) console.log(h) // [object Function]
3、instanceof
console.log([] instanceof Array) // true console.log({} instanceof Object) // true console.log(5 instanceof Number) // false console.log(new Number(5) instanceof Number) // true console.log("a" instanceof String) // false console.log(new String("a") instanceof String) // true // 注意5和new Number(5) // 5是基本数据类型,它并不是Number函数构造出来的实例对象
4、constructor
console.log([].constructor) // ƒ Array() { [native code] } console.log({}.constructor) // ƒ Object() { [native code] } console.log("a".constructor) // ƒ String() { [native code] } var num = 5 console.log(num.constructor) // ƒ Number() { [native code] } var fn = function () {} console.log(fn.constructor) // ƒ Function() { [native code] } console.log(null.constructor) // Uncaught TypeError: Cannot read property 'constructor' of null console.log(undefined.constructor) // // Uncaught TypeError: Cannot read property 'constructor' of undefined // 注意null 和 undefined, 使用constructor都会报错,所以constructor无法区分null 和undefined
5、几种特殊的数据类型 做等于判断
console.log(undefined == null) // true console.log(undefined === undefined) // true console.log(undefined == undefined) // true console.log(null === null) // true console.log(null == null) // true console.log(undefined == NaN) // false console.log(null == NaN) // false console.log(NaN == NaN) // false console.log(NaN === NaN) // false // NaN不等于任何值