判断数据类型的方法?instanceof原理?判断空对象? typeof null?typeof NaN?
程序员文章站
2024-03-17 22:31:16
...
判断数据类型的方法
typeof
判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined)
typeof判断变量是否存在(如if(typeof a!="undefined"){...})
typeof null
"object"
typeof undefined
"undefined"
typeof NaN
"number"
instanceof
A instanceof B 可以判断A是不是B的实例,返回一个布尔值,由构造类型判断出数据类型
[1,2,3] instanceof Array
true
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
Object下的toString.call()
Object.prototype.toString.call([])
"[object Array]"
Object.prototype.toString.call({})
"[object Object]"
Object.prototype.toString.call(function(){})
"[object Function]"
contructor
[].constructor
ƒ Array() { [native code] }
"123".constructor
ƒ String() { [native code] }
判断空对象
JSON.stringify()
var obj = {}
var obj1 = new Object()
JSON.stringify(obj)
"{}"
JSON.stringify(obj1)
"{}"
Object.keys
let obj3 = {}
Object.keys(obj3).length
0
Object.getOwnPropertyNames
Object.getOwnPropertyNames(obj3)
[]
obj3 = {a:1,
[Symbol('name')]: 'yr'}
{a: 1, Symbol(name): "yr"}
Object.getOwnPropertyNames(obj3)
["a"]
//判断length为0则为空对象
for...in
function isEmptyObject(obj){
for(var key in obj){
return false
};
return true
};
var a1={};
isEmptyObject(a1)
true
var b1 = {a:2}
isEmptyObject(b1)
false