js judge object attributes

1. 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; //not empty }   return true; //Empty ) console.log(empty(obj1)) //true is empty console.log(empty(obj2)) //false is not empty






Method two:
let obj1 = {}
if(JSON.stringify(obj1) == "{}"){    console.log("empty object") }else {    console.log("non-empty object") }



  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("empty object")
}else {    console.log("non-empty object") }

Second, js determines whether there is a property 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("Object has this attribute") }else {    console.log("Object does not have this attribute") }



  Method 2: in operator If a property is on the specified object or its prototype chain, it will return true. This method is not applicable when only the property of itself is judged.
let obj2 = {a:1}
if ("a" in obj2){    console.log("the object or its prototype chain has this property") }else {    console.log("the object or its prototype chain does not have this property ") }



  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("There is this property on the object") }else {    console.log("There is no such property on the object") }



Guess you like

Origin blog.csdn.net/D_J1224/article/details/107529515