typeof --返回一个字符串,表示未经计算的操作数的类型
使用方法
typeof operand
typeof(operand)
例子
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'
此处值得说一下,typeof判断null为object是一个bug,null本身不是对象,typeof不能作为判断null的方法。
同时也可以发现,引用数据类型,用typeof判断,只有function可以正确识别,其余都是object。所以typeof常用来判断基本数据类型(null除外)
instanceof() --用来判断某个元素是否某对象的构造函数实例
//使用方法
object instanceof constructor
// 定义构建函数
let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false
//可以判断数组类型
const arr = [1, 2, 3, 4]
arr instanceof Array // true
instanceof可以准确判断复杂引用数组类型,但是不能精准判断基础数据类型。
Object.prototype.toString --通用检测数据类型
Object.prototype.toString({}) // "[object Object]"
Object.prototype.toString.call({}) // 同上结果,加上call也ok
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g) //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call(document) //"[object HTMLDocument]"
Object.prototype.toString.call(window) //"[object Window]"
补充:检测数组的方法
Array.isArray() ---常用判断数组类型的方法
const arr = [1,2,3,4]
Array.isArray(arr)
console.log(Array.isArray(arr)); // true
IE9以下版本不支持,可以用其他方式判断。
instanceof() --用来判断某个元素是否某对象的构造函数实例
同上
Object.prototype.toString --通用检测数据类型
同上
constructor --通过构造函数来判定
const arr = [1, 2, 3, 4]
arr.constructor === Array // true
arr.__proto__.constructor === Array //true
小结
Object.prototype.toString是一种比较通用的检测方法。