js中判断类型的方法
栏目: JavaScript · 发布时间: 7年前
内容简介:javascript中关于类型的判断有很多种方法, 这里介绍两种常用的。typeof操作符返回一个字符串,表示未经计算的操作数的类型。在
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
以上所述就是小编给大家介绍的《js中判断类型的方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Agile Web Application Development with Yii 1.1 and PHP5
Jeffrey Winesett / Packt Publishing / 2010-08-27
In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!