美文网首页
关于js的数据类型判断

关于js的数据类型判断

作者: 柑橘与香蕉 | 来源:发表于2019-10-17 15:14 被阅读0次
微信小程序开发中遇到了需要判断数据的情况 索性总结一下

ES5中常用的数据类型有 number、string、boolean、undefined、null、object

1. typeof 可以判断基本类型 无法判断对象的具体类型 (字符串形式 需注意)例如:

let a = 1
typeof(a) === 'number' 
结果为:true

2. instanceof 已知数据是对象类型则可以使用(注意大小写)例如:

let b = [1,2,3];
b instanceof Array
结果为:true

3. Object.prototype.toString目前各大框架中常用的实现方法 (繁琐但通用)例如:

let c = 1
Object.prototype.toString.call(c)
结果为:[object Number]

一般我们会封装一下以便能够直接返回布尔值

//es5方式,返回布尔值
const isType = function(type){
  return function(obj){
        return Object.prototype.toString.call(obj) === `[object ${type}]`;
    }
};
//es6方式,返回布尔值
const isType1 = type => obj => Object.prototype.toString.call(obj) === `[object ${type}]`; 

4. 判断数组还可以用数组的isArray()方法

Array.isArray([])
结果为:true

相关文章

网友评论

      本文标题:关于js的数据类型判断

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