js中判断类型的方法

栏目: JavaScript · 发布时间: 6年前

内容简介:javascript中关于类型的判断有很多种方法, 这里介绍两种常用的。typeof操作符返回一个字符串,表示未经计算的操作数的类型。在

javascript中关于类型的判断有很多种方法, 这里介绍两种常用的。

  • typeof

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

console.log(typeof 12); // number

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

 console.log(typeof true); // boolean

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

js中判断类型的方法

这里有个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中判断类型的方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to the Design and Analysis of Algorithms

Introduction to the Design and Analysis of Algorithms

Anany Levitin / Addison Wesley / 2006-2-24 / USD 122.00

Based on a Based on a new classification of algorithm design techniques and a clear delineation of analysis methods, "Introduction to the Design and Analysis of Algorithms" presents the subject in a c......一起来看看 《Introduction to the Design and Analysis of Algorithms》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具