js各类数据类型的判断

1.typeof:

  在js中使用typeof只能判断基本数据类型,即number,string,boolean,undefined,object。对于数组函数对象等复杂类型来说,使用typeof都会统一返回object字符串。

 

2.instanceof:

  用来判断a是否为b的实例,表达式为a instanceof b ,要注意的是,instanceof检测的是原型,通俗的说instanceof用来比较一个对象是否为某一个构造函数的实例,注意,instanceof可以准确地判断复杂数据类型,但是不能正确判断基本数据类型。

复制代码
console.log(12 instanceof Number)  // false
console.log('22' instanceof String)  // false
console.log(true instanceof Boolean) // false
console.log(null instanceof Object) // false
console.log(undefined instanceof Object) // false

console.log([] instanceof Array)   // true
console.log({a: 1} instanceof Object) // true
console.log(json instanceof Object) // true
function a() {}
console.log(a instanceof Function)  // true
console.log(new Date() instanceof Date)  //true
console.log(reg instanceof RegExp) //true
console.log(error instanceof Error) // true
复制代码

3.object.prototype.toString.call()

  toString()是object的原型方法,调用该方法,默认返回当前对象的[[class]]属性,其格式为[object XXX],其中XXX就是对象的类型。对于object对象,直接调用toString()就能返回[object object]。而对于其他对象,则需要通过call/apply来调用才能返回正确的类型信息。

复制代码
console.log(Object.prototype.toString.call(1))          // [object Number]
console.log(Object.prototype.toString.call(1n))         // [object BigInt]
console.log(Object.prototype.toString.call('123'))      // [object String]
console.log(Object.prototype.toString.call(true))       // [object Boolean]
console.log(Object.prototype.toString.call(undefined))  // [object Undefined]
console.log(Object.prototype.toString.call(null))       // [object Null]
console.log(Object.prototype.toString.call({}))         // [object Object]
console.log(Object.prototype.toString.call([]))         // [object Array]
console.log(Object.prototype.toString.call(function a() {}))  // [object Function]
console.log(Object.prototype.toString.call(Symbol()))         // [object Symbol]
console.log(Object.prototype.toString.call(Math))             // [object Math]
console.log(Object.prototype.toString.call(JSON))             // [object JSON]
console.log(Object.prototype.toString.call(new Date()))       // [object Date]
console.log(Object.prototype.toString.call(new RegExp()))     // [object RegExp]
console.log(Object.prototype.toString.call(new Error))        // [object Error]
console.log(Object.prototype.toString.call(window)            // [object Window]
console.log(Object.prototype.toString.call(document)          // [object HTMLDocument]
复制代码

 

posted on   SE7EN_96  阅读(80)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示