js 数据类型判断的方法
typeof
一般用于判断基本数据类型,用于判断引用数据类型和null时会发生意外的错误
typeof 1 // numbertypeof ’1’ // stringtypeof true // booleantypeof Symbol(’1’) // symboltypeof undefined // undefinedtypeof function(){} // functiontypeof { a: 1 } // objecttypeof [1, 2, 3] // object 这里会判断异常,建议使用Array.isArray区分数组和对象//以下也会判断异常typeof new Boolean(true) === ’object’;typeof new Number(1) === ’object’;typeof new String(’abc’) === ’object’;//最后来看nulltypeof null // object
来看下typeof的原理:不同的对象在底层都表示为二进制,在js里二进制前三位都为0的会 被判断为object类型,null的二进制表示全0(对应机器码的null指针,一般为全0),所以会被判断成object类型。
instanceof
它的主要作用是用来判断一个实例是否属于某种类型,用于判断对象很合适
语法:object instanceof constructor object 某个实例对象 constructor 某个构造函数’abc’ instanceof String //false 检查原型链会返回undefinednew String(’abc’) instanceof String //truenew Boolean(true) instanceof Boolean // true new Number(1) instanceof Number // true顺便做一下简单实现function new_instance_of(leftVaule, rightVaule) { let leftProto = leftVaule.__proto__; // 取左表达式的__proto__值 let rightPrototype = rightVaule.prototype; // 取右表达式的 prototype 值 while (true) { if (leftProto === null) { return false; } if (rightPrototype === rightProto) { return true; } leftProto = leftProto.__proto__ }}
constructor
根据数据类型的构造函数返回类型,但是由于null和undefined没有构造函数故无法判断
’’.constructor == String //true new Number(1).constructor == Number //true new Function().constructor == Function //true true.constructor == Boolean //truenew Date().constructor == Date //true
Object.prototype.toString.call()
可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数。
var toString = Object.prototype.toString;toString.call(new Date); // [object Date]toString.call(new String); // [object String]toString.call(Math); // [object Math]toString.call(undefined); // [object Undefined]toString.call(null); // [object Null]
lodash.getTag和lodash.baseGetTag
baseGetTag使用Object.prototype.toString.call和Symbol.toStringTag来判断属性的类型Symbol.toStringTag只适合做特定的类型判断
//lodash.baseGetTag部分重要源码//如果值是undefined和null返回对应tag if (value == null) { return value === undefined ? ’[object Undefined]’ : ’[object Null]’ } // 如果不支持Symbol或者value值上面没有Symbol.toStringTag属性, //直接返回Object.prototype.toString调用后的值 if (!(symToStringTag && symToStringTag in Object(value))) { return toString.call(value) }
以上就是js 数据类型判断的方法的详细内容,更多关于js 数据类型判断的资料请关注好吧啦网其它相关文章!
相关文章:
1. python基于scrapy爬取京东笔记本电脑数据并进行简单处理和分析2. 详解Android跨进程通信之AIDL3. Java 如何实现AES加密4. Python csv文件记录流程代码解析5. Windows+Apache搭建PHP开发环境6. Django自带用户认证系统使用方法解析7. 在Spring 中使用@Aspect 控制自定义注解的操作8. django admin search_fields placeholder 管理后台添加搜索框提示文字9. Django model class Meta原理解析10. set rs=conn.execute,set rs=server.createobject(“ADODB.recordset”)的性能对比