继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

javascript判断数据类型的方法

记得丶微笑
关注TA
已关注
手记 7
粉丝 1
获赞 4

1. typeof操作符

typeof "John"                // 返回 string
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean
typeof [1,2,3,4]             // 返回 object
typeof {name:'John', age:34} // 返回 object

typeof只支持数字、字符串、布尔以及对象的判断。

2. Object原型方法

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

Object原型方法支持所有数据类型的判断。

3. constructor

''.constructor == String  // true
1.constructor == Number // true
[].constructor == Array // true
new Array().constructor == Arra y// true
{}.constructor == Object // true
new Function().constructor == Function // true
new Date().constructor == Date // true

注意:null 和 undefined 无constructor,因此constructor无法判断null 和 undefined这两种类型。

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP