前端数据类型判断
2019-11-14 本文已影响0人
暴躁肥猫
闲来无事,控制台打印着玩
![](https://img.haomeiwen.com/i16482960/a3546382b764dfb2.png)
== 和 === 判断的区别:
== 表示相等 (值相等)
===表示恒等(类型和值都要相等)
例:1=='1':true
1==='1' false
数据类型判断:
![](https://img.haomeiwen.com/i16482960/24e4621c640a91b2.png)
使用typeof判断数组和对象都会返回object
还有例如typeof(Number) typeof(Number(10)) typeof(new Number(10)) 都会不一样
对于Array和Object 对象的检测,这里方法可以参考一下:
1.对于Es5,变量名字.isArray( )可以实现这个目的
var a=[];
var b={};
Array.isArray(a);//true
Array.isArray(b)//false
2.对于大部分主流,一般都使用这个方法
if (!Array.isArray){
Array.isArray = function(arg){
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
对于是不是对象:
1.toString方法 (推荐)
Object.prototype.toString.call(obj) === '[Object Object]'
2、constructor
obj.constructor === Object
3、instanceof 需要注意的是由于数组也是对象,因此用 arr instanceof Object 也为true。
obj instanceof Object
4、typeof
typeof obj === Object
// 根据typeof判断对象也不太准确
表达式 返回值
typeof undefined 'undefined'
typeof null 'object'
typeof true 'boolean'
typeof 123 'number'
typeof "abc" 'string'
typeof function() {} 'function'
typeof {} 'object'
typeof [] 'object'