使用Object.prototype.toString.call进行数据类型判断的意义在于:
1.typeof
typeof 返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、symbol、object、undefined、function等7 种数据类型,但不能判断object,null、array等数组和对象返回的都是object,就要使instanceof 来判断
2.instanceof
instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
3.[] instanceof Array; //true
关于数组的类型判断,还可以用ES6 新增Array.isArray()对于基本数据类型来说,不能使用。字面量方式创建出来的结果和实例方式创建的是有一定的区别的,不能检测null 和 undefined
4.constructor
constructor 作用和 instanceof 非常相似。但 constructor 检测 Object 与 instanceof 不一样,还可以处理基本数据类型的检测。
constructor 两大弊端:
null 和 undefined 是无效的对象,
数据类型判断
1.js数据类型:
Type: function (obj) {
let str = Object.prototype.toString.call(obj)
return str.slice(8, str.length - 1);
}
用法:Type('123')
2.js数据类型判断:
isType: function (type, obj) {
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
用法:isType('String','123')
数据类型空值判断
包括:
- 1.null,
- 2.undefined,
- 3."null",
- 4."undefined",
- 5.{},
- 6."{}",
- 7.[],
- 8."[]",
- 9.0,
- 10.true,
- 11."true";
以上js空值判断,值为真的返回true,空值为false
//空值判断
isNotEmpty: function (obj) {
switch (Object.prototype.toString.call(obj)) {
case '[object Number]':
if (obj > 0) {
return true;
};
return false;
case '[object String]':
try {
let StringObj = Object.prototype.toString.call(JSON.parse(obj));
let ObjcetObj = JSON.parse(obj);
switch (StringObj) {
case '[object Number]':
if (ObjcetObj > 0) {
return true;
};
return false;
case '[object Array]':
if (ObjcetObj.length > 0) {
return true;
};
return false;
case '[object Boolean]':
if (ObjcetObj) {
return true;
};
return false;
case '[object Undefined]':
return false;
case '[object Null]':
return false;
case '[object Object]':
if (Object.getOwnPropertyNames(ObjcetObj).length > 0) {
return true;
};
return false;
default:
break;
};
} catch (error) {
if (obj && obj.length > 0 && obj !== "undefined") {
return true;
};
return false;
};
case '[object Array]':
if (obj.length > 0) {
return true;
};
return false;
case '[object Boolean]':
if (obj) {
return true;
};
return false;
case '[object Undefined]':
return false;
case '[object Null]':
return false;
case '[object Object]':
if (Object.getOwnPropertyNames(obj).length > 0) {
return true;
};
return false;
default:
break;
}
},
使用方法:isEmpty(aaa)
1.处理成想要的格式数据
let aaa=""||"null"||"[]"||"{}"||"0"||"false"||"undefined " (或为异步未知类型数据)
aaa=isNotEmpty(aaa) ? aaa : 0
2. if判断
if(isNotEmpty(aaa)){
//字段渲染
//表格渲染
}else{
//数据为空的处理方法
}
如果有什么问题和疑问请在下方留言,文章为原创,转载请注明!