栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js 数据类型判断的方法

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js 数据类型判断的方法

typeof

一般用于判断基本数据类型,用于判断引用数据类型和null时会发生意外的错误

typeof 1 // number
typeof '1' // string
typeof true // boolean
typeof Symbol('1') // symbol
typeof undefined // undefined

typeof function(){} // function
typeof { a: 1 } // object
typeof [1, 2, 3] // object 这里会判断异常,建议使用Array.isArray区分数组和对象

//以下也会判断异常
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';

//最后来看null
typeof null // object

来看下typeof的原理:不同的对象在底层都表示为二进制,在js里二进制前三位都为0的会 被判断为object类型,null的二进制表示全0(对应机器码的null指针,一般为全0),所以会被判断成object类型。

instanceof

它的主要作用是用来判断一个实例是否属于某种类型,用于判断对象很合适

语法:object instanceof constructor 
object 某个实例对象 constructor 某个构造函数

'abc' instanceof String //false 检查原型链会返回undefined
new String('abc') instanceof String //true
new 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  //true
new 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 数据类型判断的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/67466.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号