您的位置:首页技术文章
文章详情页

js 数据类型判断的方法

【字号: 日期:2024-04-11 08:31:06浏览:42作者:猪猪

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只适合做特定的类型判断

js 数据类型判断的方法

//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 数据类型判断的资料请关注好吧啦网其它相关文章!

标签: JavaScript
相关文章: