js中判断类型的方法

javascript中关于类型的判断有不少种方法, 这里介绍两种经常使用的。javascript

  • typeof

typeof操做符返回一个字符串,表示未经计算的操做数的类型。java

console.log(typeof 12); // number

 console.log(typeof 'hello'); // string

 console.log(typeof true); // boolean

MDN中, typeof的用法记录的很详细。性能

clipboard.png

这里有个js的关键点, 即typeof null == object。 null 不是一个对象,尽管 typeof null 输出的是 object,这是一个历史遗留问题,JS 的最第一版本中使用的是 32 位系统,为了性能考虑使用低位存储变量的类型信息,000 开头表明是对象, null 表示为全零,因此将它错误的判断为 object 。spa

正由于typeof不能准确判断一个对象变量, 因此须要下面一种方法prototype

  • Object.prototype.toString.call

使用Object.prototype上的原生toString()方法判断数据类型code

console.log( Object.prototype.toString.call( 'hello' )) // [object String]

 console.log( Object.prototype.toString.call( 1 )) // [object Number]

 console.log( Object.prototype.toString.call( [1, 2, 3] )) // [object Array]

 console.log( Object.prototype.toString.call( null )) // [object Null]

能够将这样的一长串代码封装成检测类型的方法对象

let isType = type => obj => {
  return Object.prototype.toString.call( obj ) === `[object ${type}]`
}

isType('String')('123');       // true
isType('Array')([1, 2, 3]);    // true
isType('Number')(1);           // true
相关文章
相关标签/搜索