How does JS judge whether an object is empty and whether it has a certain attribute

One, js judges whether an object is empty

method one:

let obj1 = {}
let obj2 = {a:1}
function empty(obj){
for (let key in obj){
  return false;    //非空
}
return true;       //为空
}
console.log(empty(obj1)) //true为空
console.log(empty(obj2)) //false非空

Method Two:

let obj1 = {}
if(JSON.stringify(obj1) == "{}"){
   console.log("空对象")
}else {
   console.log("非空对象")
}

Method 3: Object.keys(obj) returns an array of enumerable properties of the given object itself.

let obj1 = {}
if (Object.keys(obj1).length == 0){   
   console.log("空对象")
}else {
   console.log("非空对象")
}

Two, js judges whether there is a certain attribute in the object

Method 1:. Or [] When the value of this property is false, undefined, NaN, null, 0, "", this method is not applicable.

if (obj2.a){
   console.log("对象有此属性")
}else {
   console.log("对象无此属性")
}

Method 2: The in operator returns true if an attribute is on the specified object or its prototype chain, and this method is not applicable when it only needs to judge its own attributes.

let obj2 = {a:1}
if ("a" in obj2){
   console.log("对象或其原型链上有此属性")
}else {
   console.log("对象或其原型链上无此属性")
}

Method 3: obj.hasOwnProperty() object contains a property in its own property, and returns true.

let obj2 = {a:1}
if (obj2.hasOwnProperty("a")){
   console.log("对象上有此属性")
}else {
   console.log("对象上无此属性")
}

Guess you like

Origin blog.csdn.net/weixin_49666910/article/details/113373931