js a determination object object is empty

Method one: Use for ... in

for...in... Traversing the property, as was true "non-empty array"; otherwise, "empty array"

for (var i in obj) {

     return true   // if not empty, will perform this step, return true

}

return false // if empty, return false

Option two: the JSON.stringify ()

JSON Own  stringify() method for the  JavaScript value into  JSON a string

if (JSON.stringify(data) === '{}') {

  return false // if empty, return false

}

return true // if not empty, will perform this step, return true

Method three: Use Object.keys ()

ES6 The new method of  Object.keys():Object.keys() method returns an array of a given object itself may be enumerated properties thereof.

If our object is empty, he will return an empty array, as follows:

There are a = {}

Object.keys(a) // []

Can rely Object.keys () This method to know whether it is empty by determining its length

if (Object.keys(object).length === 0) {

  return false // if empty, return false

}

return true // if not empty, will perform this step, return true

Or write in a function

function checkNullObj (obj) {

  return Object.keys(obj).length === 0

}

 

Guess you like

Origin www.cnblogs.com/kunmomo/p/11751744.html