美文网首页面试前的准备前端小喵
javascript数据类型判断方法

javascript数据类型判断方法

作者: 明眸yh | 来源:发表于2020-05-22 18:55 被阅读0次

1.typeof判断类型

typeof 1 // number
typeof NaN // number
typeof '1' // string
typeof true // boolean
typeof undefined // undefined
typeof new Date() // object
typeof null // object
typeof /^\d/g // object
typeof [] // object
typeof {} // object
typeof Symbol(1) // symbol

2.Object.prototype.toString判断类型

Object.prototype.toString.call(1)  // [object Number]
Object.prototype.toString.call(NaN) // [object Number]
Object.prototype.toString.call('1') // [object String]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(new Date ()) // [object Date]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(/^\d/g) // [object RegExp]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call({}) // [object Object]
Object.prototype.toString.call(Symbol(2)) // [object Symbol]

3.instanceof判断类型

如果变量是给定引用类型的实例,那么instanceof操作符就会返回true

[] instanceof Array // true
{} instanceof Object // true
/^\d/g instanceof RegExp // true

根据规定,所有引用类型的值都是Object的实例。因此,在检测一个引用类型值和Object构造函数时,instanceof操作符始终会返回true。当然,如果使用instanceof操作符检测基本类型的值,则
该操作符始终会返回false,因为基本类型不是对象。
instanceof操作符的问题在于,它假定只有一个全局执行环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的Array构造函数。

作者:ZhangCheng
链接:https://juejin.im/post/5acb14da6fb9a028c71ebe60
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

网友评论

    本文标题:javascript数据类型判断方法

    本文链接:https://www.haomeiwen.com/subject/xphfxqtx.html