javascript中关于范例的推断有许多种要领, 这里引见两种经常运用的。
- typeof
typeof操作符返回一个字符串,示意未经盘算的操作数的范例。
console.log(typeof 12); // number
console.log(typeof 'hello'); // string
console.log(typeof true); // boolean
在MDN中, typeof的用法纪录的很细致。
这里有个js的症结点, 即typeof null == object。 null 不是一个对象,只管 typeof null 输出的是 object,这是一个汗青遗留问题,JS 的最初版本中运用的是 32 位体系,为了机能斟酌运用低位存储变量的范例信息,000 开首代表是对象, null 示意为全零,所以将它毛病的推断为 object 。
正因为typeof不能正确推断一个对象变量, 所以须要下面一种要领
- Object.prototype.toString.call
运用Object.prototype上的原生toString()要领推断数据范例
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