Js how to determine whether the Object is empty?

Js how to determine whether the Object is empty? (Attribute is empty)

When using JavaScript, you will meet from time to time to determine how an object Object is empty, so summary a little, easy access, I usually use 方法二.

js 判断一个 object 对象是否为空,下面汇总了几种判断方法:

Method One: The most common way of thinking, for...in...traverse the property, as was true 非空数组" "; otherwise, 空数组" "

for (var i in obj) { // 如果不为空,则会执行到这一步,返回true
    return true
}
return false // 如果为空,返回false

Method two: by JSONcarrying stringify()judged Method:

The JSON.stringify () method is used to convert the value to JavaScript JSON string.

    if (JSON.stringify(data) === '{}') {
        return false // 如果为空,返回false
    }
    return true // 如果不为空,则会执行到这一步,返回true

It should be noted Why not toString (), because it returns is not what we need.

    var a = {}
    a.toString() // "[object Object]"

Method three: ES6 new method 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:

    var a = {}
    Object.keys(a) // []

We can rely on Object.keys () this method to know if it is empty by determining its length.

    if (Object.keys(object).length === 0) {
        return false // 如果为空,返回false
    }
    return true // 如果不为空,则会执行到这一步,返回true

Method four: jquerythe isEmptyObjectmethod

This is the second method jquery (for in) encapsulated need to rely on the use jquery

    var data = {};
    var b = $.isEmptyObject(data);
    alert(b);//true

Guess you like

Origin www.cnblogs.com/LiangSenCheng/p/12521547.html