如何测试一个空的JavaScript对象?

时间:2022-05-15 07:21:09

After an AJAX request, sometimes my application may return an empty object, like:

在AJAX请求之后,有时我的应用程序可能会返回一个空对象,比如:

var a = {};

How can I check whether that's the case?

我怎么检查这是不是真的?

40 个解决方案

#1


2703  

ECMA 5+:

ECMA 5 +:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object

Pre-ECMA 5:

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

lodash:

_.isEmpty({}); // true

Underscore:

强调:

_.isEmpty({}); // true

Hoek

隐谷

Hoek.deepEqual({}, {}); // true

ExtJS

ExtJS

Ext.Object.isEmpty({}); // true

AngularJS (version 1)

AngularJS(版本1)

angular.equals({}, {}); // true

Ramda

Ramda

R.isEmpty({}); // true

#2


727  

There's no easy way to do this. You'll have to loop over the properties explicitly:

没有简单的方法。你必须明确地对属性进行循环:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

If ECMAScript 5 support is available, you can use Object.keys() instead:

如果ECMAScript 5支持可用,则可以使用Object.keys():

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

#3


535  

For those of you who have the same problem but uses jQuery, you can use jQuery.isEmptyObject.

对于那些有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。

#4


180  

You can use Underscore.js.

您可以使用Underscore.js。

_.isEmpty({}); // true

#5


161  

This is my preferred solution:

这是我最喜欢的解决方案:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty

#6


101  

if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/

参见http://bencollier.net/2011/04/javascript-is-an-object-empty/

#7


63  

How about using JSON.stringify? It is almost available in all modern browsers.

使用JSON.stringify怎么样?它几乎可以在所有的现代浏览器中使用。

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}

#8


50  

Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:

老问题,只是有问题。如果您的唯一目的是检查对象是否为空,那么包括JQuery并不是一个好主意。相反,只要深入JQuery的代码,你就会得到答案:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

#9


36  

I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

我遇到了类似的情况。我不想使用JQuery,而是使用纯Javascript来实现。

And what I did was, used the following condition, and it worked for me.

我所做的是,使用了下面的条件,它对我有效。

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

不等于,使用这个:JSON.stringify(obj) !== '{}

Check out this JSFiddle

看看这个JSFiddle

#10


20  

I've created a complete function to determine if object is empty.

我创建了一个完整的函数来确定对象是否为空。

It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

它使用对象。如果可能的话,从ECMAScript 5 (ES5)的功能可以获得最佳性能(参见兼容性表),并支持旧引擎(浏览器)最兼容的方法。

Solution

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

Here's the Gist for this code.

下面是代码的要点。

And here's the JSFiddle with demonstration and a simple test.

这是js小提琴的演示和一个简单的测试。

I hope it will help someone. Cheers!

我希望它能帮助别人。干杯!

#11


18  

There is a simple way if you are on a newer browser. Object.keys(obj).length == 0

如果你在一个较新的浏览器上,有一个简单的方法。种(obj)。长度= = 0

#12


17  

  1. Just a workaround. Can your server generate some special property in case of no data?

    只是一个解决方案。如果没有数据,您的服务器能生成一些特殊的属性吗?

    For example:

    例如:

    var a = {empty:true};
    

    Then you can easily check it in your AJAX callback code.

    然后,您可以轻松地在AJAX回调代码中检查它。

  2. Another way to check it:

    另一种检查方法:

    if (a.toSource() === "({})")  // then 'a' is empty
    

EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.

编辑:如果您使用任何JSON库(f.e. JSON.js),那么您可以尝试JSON.encode()函数并对空值字符串进行测试。

#13


14  

I am using this.

我使用这个。

function isObjectEmpty(object)
{
  var isEmpty = true;
  for(keys in object)
  {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

例如:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

from here

从这里

Update

更新

OR

you can use the jQuery implementation of isEmptyObject

您可以使用isEmptyObject的jQuery实现。

function isEmptyObject ( obj ) {
        var name;
        for ( name in obj ) {
            return false;
        }
        return true;
    }

#14


13  

Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.

使用种(obj)。长度(如上面建议的ECMA 5+)是空对象的10倍慢!与旧学校保持联系。

Tested under Node, Chrom, Firefox and IE 9, it becomes evident that for most use cases:

在Node、Chrom、Firefox和ie9的测试下,对于大多数用例来说,很明显:

  • (for...in...) is the fastest option to use!
  • (for…in…)是最快的选择!
  • Object.keys(obj).length is 10 times slower for empty objects
  • 种(obj)。对于空对象,长度是慢10倍。
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • JSON.stringify(obj)。长度总是最慢的(而不是令人惊讶的)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.
  • Object.getOwnPropertyNames(obj)。长度比Object.keys(obj)要长。在某些系统上,长度可能要长得多。

Bottom line performance wise, use:

底线表现明智,使用:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

See detailed testing results and test code at Is object empty?

查看详细的测试结果和测试代码是否为空?

#15


10  

function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}

#16


8  

jQuery have special function isEmptyObject() for this case:

对于这种情况,jQuery具有特殊的函数isEmptyObject():

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

Read more on http://api.jquery.com/jQuery.isEmptyObject/

在http://api.jquery.com/jQuery.isEmptyObject/上阅读更多

#17


8  


you can use this simple code that did not use jQuery or other libraries

您可以使用不使用jQuery或其他库的简单代码。

var a=({});

//check is an empty object
if(JSON.stringify(a)=='{}') {
    alert('it is empty');
} else {
    alert('it is not empty');
}

JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.

Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.

JSON类和它的函数(parse和stringify)非常有用,但是IE7有一些问题,您可以用这个简单的代码来修复它。其他简单的方法(最简单的方法):不用jQuery或JSON对象就可以使用这种方法。

var a=({});

function isEmptyObject(obj) {
    if(typeof obj!='object') {
        //it is not object, so is not empty
        return false;
    } else {
        var x,i=0;
        for(x in obj) {
            i++;
        }
        if(i>0) {
            //this object has some properties or methods
            return false;
        } else {
            //this object has not any property or method
            return true;
        }
    }
}

alert(isEmptyObject(a));    //true is alerted

#18


7  

If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.

如果jQuery和web浏览器不可用,那么在underscore.js中也有一个isEmpty函数。

_.isEmpty({}) // returns true

Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.

此外,它不假定输入参数为对象。对于一个列表或字符串或未定义的字符串,它也会给出正确的答案。

#19


7  

Best way that I found:

我找到的最好的方法:

function isEmpty(obj)
{
    if (!obj)
    {
        return true;
    }

    if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
    {
        return true;
    }

    return false;
}

Works for:

适用于:

    t1: {} -> true
    t2: {0:1} -: false
    t3: [] -> true
    t4: [2] -> false
    t5: null -> true
    t6: undefined -> true
    t7: "" -> true
    t8: "a" -> false
    t9: 0 -> true
    t10: 1 -> false

#20


6  

My take:

我采用的方法:

function isEmpty(obj) {
    return !Object.keys(obj).length > 0;
}

var a = {a:1, b:2}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

Just, I don't think all browsers implement Object.keys() currently.

只是,我不认为所有的浏览器都实现了Object.keys()。

#21


6  

You could check for the count of the Object keys:

您可以检查对象键的计数:

if (Object.keys(a).length > 0) {
    // not empty
}

#22


6  

The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.

下面的示例演示如何测试一个JavaScript对象是否为空,如果是空的,则表示没有自己的属性。

The script works on ES6.

该脚本适用于ES6。

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0 ? true : false;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true

#23


5  

A simple loop:

一个简单的循环:

var is_empty = true;
for(var i in obj) {
    is_empty = false;
    break;
}

#24


4  

Another simple, pure JS way :)

另一个简单的,纯JS的方式:)

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

如果(JSON.stringify(pathParams)= = =“{ }”)

#25


3  

In addition to Thevs answer:

除了vs回答:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json

这是jquery + jquery.json

#26


3  

Caveat! Beware of JSON's limitiations.

警告!谨防JSON limitiations。

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

displays

显示

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}

#27


3  

Sugar.JS provides extended objects for this purpose. The code is clean and simple:

糖。JS为这个目的提供了扩展的对象。代码简洁明了:

Make an extended object:

做一个扩展的对象:

a = Object.extended({})

Check it's size:

检查它的大小:

a.size()

#28


2  

this one line code helps

这一行代码有帮助。

var a = {}; //if empty returns false
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns False

var a = {b:2} //if not empty returns true
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns true

Object.getOwnPropertyNames is implemented in ECMA-5. the above line works in older browsers with a fallback function.

对象。getOwnPropertyNames是在ECMA-5中实现的。上面的代码在旧的浏览器中工作,具有一个回退函数。

JSFiddler

JSFiddler

#29


2  

Another alternative is to use is.js (14kB) as opposed to jquery (32kB), lodash (50kB), or underscore (16.4kB). is.js proved to be the fastest library among aforementioned libraries that could be used to determine whether an object is empty.

另一种选择是使用is。与jquery (32kB)、lodash (50kB)或下划线(16.4kB)相比,js (14kB)。是多少。js被证明是前面提到的库中最快的库,可以用来确定一个对象是否为空。

http://jsperf.com/check-empty-object-using-libraries

http://jsperf.com/check-empty-object-using-libraries

Obviously all these libraries are not exactly the same so if you need to easily manipulate the DOM then jquery might still be a good choice or if you need more than just type checking then lodash or underscore might be good. As for is.js, here is the syntax:

显然,所有这些库都不是完全相同的,因此如果您需要轻松地操作DOM,那么jquery可能仍然是一个不错的选择,或者如果您需要的不仅仅是类型检查,那么lodash或下划线可能很好。至于。js,这里是语法:

var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false

Like underscore's and lodash's _.isObject(), this is not exclusively for objects but also applies to arrays and strings.

与下划线和lodash的_.isObject()一样,这不仅仅适用于对象,也适用于数组和字符串。

Under the hood this library is using Object.getOwnPropertyNames which is similar to Object.keys but Object.getOwnPropertyNames is a more thorough since it will return enumerable and non-enumerable properties as described here.

在引擎盖下,这个库使用对象。类似于对象的getOwnPropertyNames。钥匙但是对象。getOwnPropertyNames更加彻底,因为它将返回这里描述的可枚举和不可枚举属性。

is.empty = function(value) {
    if(is.object(value)){
        var num = Object.getOwnPropertyNames(value).length;
        if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
            return true;
        }
        return false;
    } else {
        return value === '';
    }
};

If you don't want to bring in a library (which is understandable) and you know that you are only checking objects (not arrays or strings) then the following function should suit your needs.

如果您不想引入一个库(这是可以理解的),并且您知道您只是在检查对象(不是数组或字符串),那么下面的函数应该适合您的需要。

function isEmptyObject( obj ) {
    return Object.getOwnPropertyNames(obj).length === 0;
}

This is only a bit faster than is.js though just because you aren't checking whether it is an object.

这个速度比原来快了一点。js只是因为你没有检查它是否是一个对象。

#30


2  

I can't believe after two years of programming js it never clicked that empty objects and array's aren't falsey, the weirdest thing is it never caught me out.

我不相信经过两年的编程js,它从来没有点击过空的对象和数组的不是falsey,最奇怪的是它从来没有被我发现。

this will return true if the input is falsey by default or if it's an empty object or array. the inverse is the trueish function

如果默认输入是falsey,或者是空的对象或数组,这将返回true。逆是trueish函数。

http://codepen.io/synthet1c/pen/pjmoWL

http://codepen.io/synthet1c/pen/pjmoWL

function falsish( obj ){
    if( (typeof obj === 'number' && obj > 0) || obj === true ){
        return false;
    }
    return !!obj
        ? !Object.keys( obj ).length
        : true;
}

function trueish( obj ){
    return !falsish( obj );
}

falsish({})           //=> true
falsish({foo:'bar'})  //=> false
falsish([])           //=> true
falsish(['foo'])      //=> false
falsish(false)        //=> true
falsish(true)         //=> false
// the rest are on codepen

#1


2703  

ECMA 5+:

ECMA 5 +:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object

Pre-ECMA 5:

Pre-ECMA 5:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

lodash:

_.isEmpty({}); // true

Underscore:

强调:

_.isEmpty({}); // true

Hoek

隐谷

Hoek.deepEqual({}, {}); // true

ExtJS

ExtJS

Ext.Object.isEmpty({}); // true

AngularJS (version 1)

AngularJS(版本1)

angular.equals({}, {}); // true

Ramda

Ramda

R.isEmpty({}); // true

#2


727  

There's no easy way to do this. You'll have to loop over the properties explicitly:

没有简单的方法。你必须明确地对属性进行循环:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}

If ECMAScript 5 support is available, you can use Object.keys() instead:

如果ECMAScript 5支持可用,则可以使用Object.keys():

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

#3


535  

For those of you who have the same problem but uses jQuery, you can use jQuery.isEmptyObject.

对于那些有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。

#4


180  

You can use Underscore.js.

您可以使用Underscore.js。

_.isEmpty({}); // true

#5


161  

This is my preferred solution:

这是我最喜欢的解决方案:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty

#6


101  

if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/

参见http://bencollier.net/2011/04/javascript-is-an-object-empty/

#7


63  

How about using JSON.stringify? It is almost available in all modern browsers.

使用JSON.stringify怎么样?它几乎可以在所有的现代浏览器中使用。

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}

#8


50  

Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:

老问题,只是有问题。如果您的唯一目的是检查对象是否为空,那么包括JQuery并不是一个好主意。相反,只要深入JQuery的代码,你就会得到答案:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}

#9


36  

I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

我遇到了类似的情况。我不想使用JQuery,而是使用纯Javascript来实现。

And what I did was, used the following condition, and it worked for me.

我所做的是,使用了下面的条件,它对我有效。

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

不等于,使用这个:JSON.stringify(obj) !== '{}

Check out this JSFiddle

看看这个JSFiddle

#10


20  

I've created a complete function to determine if object is empty.

我创建了一个完整的函数来确定对象是否为空。

It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

它使用对象。如果可能的话,从ECMAScript 5 (ES5)的功能可以获得最佳性能(参见兼容性表),并支持旧引擎(浏览器)最兼容的方法。

Solution

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

Here's the Gist for this code.

下面是代码的要点。

And here's the JSFiddle with demonstration and a simple test.

这是js小提琴的演示和一个简单的测试。

I hope it will help someone. Cheers!

我希望它能帮助别人。干杯!

#11


18  

There is a simple way if you are on a newer browser. Object.keys(obj).length == 0

如果你在一个较新的浏览器上,有一个简单的方法。种(obj)。长度= = 0

#12


17  

  1. Just a workaround. Can your server generate some special property in case of no data?

    只是一个解决方案。如果没有数据,您的服务器能生成一些特殊的属性吗?

    For example:

    例如:

    var a = {empty:true};
    

    Then you can easily check it in your AJAX callback code.

    然后,您可以轻松地在AJAX回调代码中检查它。

  2. Another way to check it:

    另一种检查方法:

    if (a.toSource() === "({})")  // then 'a' is empty
    

EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.

编辑:如果您使用任何JSON库(f.e. JSON.js),那么您可以尝试JSON.encode()函数并对空值字符串进行测试。

#13


14  

I am using this.

我使用这个。

function isObjectEmpty(object)
{
  var isEmpty = true;
  for(keys in object)
  {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

例如:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

from here

从这里

Update

更新

OR

you can use the jQuery implementation of isEmptyObject

您可以使用isEmptyObject的jQuery实现。

function isEmptyObject ( obj ) {
        var name;
        for ( name in obj ) {
            return false;
        }
        return true;
    }

#14


13  

Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.

使用种(obj)。长度(如上面建议的ECMA 5+)是空对象的10倍慢!与旧学校保持联系。

Tested under Node, Chrom, Firefox and IE 9, it becomes evident that for most use cases:

在Node、Chrom、Firefox和ie9的测试下,对于大多数用例来说,很明显:

  • (for...in...) is the fastest option to use!
  • (for…in…)是最快的选择!
  • Object.keys(obj).length is 10 times slower for empty objects
  • 种(obj)。对于空对象,长度是慢10倍。
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • JSON.stringify(obj)。长度总是最慢的(而不是令人惊讶的)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.
  • Object.getOwnPropertyNames(obj)。长度比Object.keys(obj)要长。在某些系统上,长度可能要长得多。

Bottom line performance wise, use:

底线表现明智,使用:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

See detailed testing results and test code at Is object empty?

查看详细的测试结果和测试代码是否为空?

#15


10  

function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}

#16


8  

jQuery have special function isEmptyObject() for this case:

对于这种情况,jQuery具有特殊的函数isEmptyObject():

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

Read more on http://api.jquery.com/jQuery.isEmptyObject/

在http://api.jquery.com/jQuery.isEmptyObject/上阅读更多

#17


8  


you can use this simple code that did not use jQuery or other libraries

您可以使用不使用jQuery或其他库的简单代码。

var a=({});

//check is an empty object
if(JSON.stringify(a)=='{}') {
    alert('it is empty');
} else {
    alert('it is not empty');
}

JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.

Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.

JSON类和它的函数(parse和stringify)非常有用,但是IE7有一些问题,您可以用这个简单的代码来修复它。其他简单的方法(最简单的方法):不用jQuery或JSON对象就可以使用这种方法。

var a=({});

function isEmptyObject(obj) {
    if(typeof obj!='object') {
        //it is not object, so is not empty
        return false;
    } else {
        var x,i=0;
        for(x in obj) {
            i++;
        }
        if(i>0) {
            //this object has some properties or methods
            return false;
        } else {
            //this object has not any property or method
            return true;
        }
    }
}

alert(isEmptyObject(a));    //true is alerted

#18


7  

If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.

如果jQuery和web浏览器不可用,那么在underscore.js中也有一个isEmpty函数。

_.isEmpty({}) // returns true

Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.

此外,它不假定输入参数为对象。对于一个列表或字符串或未定义的字符串,它也会给出正确的答案。

#19


7  

Best way that I found:

我找到的最好的方法:

function isEmpty(obj)
{
    if (!obj)
    {
        return true;
    }

    if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
    {
        return true;
    }

    return false;
}

Works for:

适用于:

    t1: {} -> true
    t2: {0:1} -: false
    t3: [] -> true
    t4: [2] -> false
    t5: null -> true
    t6: undefined -> true
    t7: "" -> true
    t8: "a" -> false
    t9: 0 -> true
    t10: 1 -> false

#20


6  

My take:

我采用的方法:

function isEmpty(obj) {
    return !Object.keys(obj).length > 0;
}

var a = {a:1, b:2}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

Just, I don't think all browsers implement Object.keys() currently.

只是,我不认为所有的浏览器都实现了Object.keys()。

#21


6  

You could check for the count of the Object keys:

您可以检查对象键的计数:

if (Object.keys(a).length > 0) {
    // not empty
}

#22


6  

The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.

下面的示例演示如何测试一个JavaScript对象是否为空,如果是空的,则表示没有自己的属性。

The script works on ES6.

该脚本适用于ES6。

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0 ? true : false;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true

#23


5  

A simple loop:

一个简单的循环:

var is_empty = true;
for(var i in obj) {
    is_empty = false;
    break;
}

#24


4  

Another simple, pure JS way :)

另一个简单的,纯JS的方式:)

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

如果(JSON.stringify(pathParams)= = =“{ }”)

#25


3  

In addition to Thevs answer:

除了vs回答:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json

这是jquery + jquery.json

#26


3  

Caveat! Beware of JSON's limitiations.

警告!谨防JSON limitiations。

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

displays

显示

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}

#27


3  

Sugar.JS provides extended objects for this purpose. The code is clean and simple:

糖。JS为这个目的提供了扩展的对象。代码简洁明了:

Make an extended object:

做一个扩展的对象:

a = Object.extended({})

Check it's size:

检查它的大小:

a.size()

#28


2  

this one line code helps

这一行代码有帮助。

var a = {}; //if empty returns false
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns False

var a = {b:2} //if not empty returns true
(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (function(){for(var key in a) break; return (key != null) && (key != undefined);})()) //Returns true

Object.getOwnPropertyNames is implemented in ECMA-5. the above line works in older browsers with a fallback function.

对象。getOwnPropertyNames是在ECMA-5中实现的。上面的代码在旧的浏览器中工作,具有一个回退函数。

JSFiddler

JSFiddler

#29


2  

Another alternative is to use is.js (14kB) as opposed to jquery (32kB), lodash (50kB), or underscore (16.4kB). is.js proved to be the fastest library among aforementioned libraries that could be used to determine whether an object is empty.

另一种选择是使用is。与jquery (32kB)、lodash (50kB)或下划线(16.4kB)相比,js (14kB)。是多少。js被证明是前面提到的库中最快的库,可以用来确定一个对象是否为空。

http://jsperf.com/check-empty-object-using-libraries

http://jsperf.com/check-empty-object-using-libraries

Obviously all these libraries are not exactly the same so if you need to easily manipulate the DOM then jquery might still be a good choice or if you need more than just type checking then lodash or underscore might be good. As for is.js, here is the syntax:

显然,所有这些库都不是完全相同的,因此如果您需要轻松地操作DOM,那么jquery可能仍然是一个不错的选择,或者如果您需要的不仅仅是类型检查,那么lodash或下划线可能很好。至于。js,这里是语法:

var a = {};
is.empty(a); // true
is.empty({"hello": "world"}) // false

Like underscore's and lodash's _.isObject(), this is not exclusively for objects but also applies to arrays and strings.

与下划线和lodash的_.isObject()一样,这不仅仅适用于对象,也适用于数组和字符串。

Under the hood this library is using Object.getOwnPropertyNames which is similar to Object.keys but Object.getOwnPropertyNames is a more thorough since it will return enumerable and non-enumerable properties as described here.

在引擎盖下,这个库使用对象。类似于对象的getOwnPropertyNames。钥匙但是对象。getOwnPropertyNames更加彻底,因为它将返回这里描述的可枚举和不可枚举属性。

is.empty = function(value) {
    if(is.object(value)){
        var num = Object.getOwnPropertyNames(value).length;
        if(num === 0 || (num === 1 && is.array(value)) || (num === 2 && is.arguments(value))){
            return true;
        }
        return false;
    } else {
        return value === '';
    }
};

If you don't want to bring in a library (which is understandable) and you know that you are only checking objects (not arrays or strings) then the following function should suit your needs.

如果您不想引入一个库(这是可以理解的),并且您知道您只是在检查对象(不是数组或字符串),那么下面的函数应该适合您的需要。

function isEmptyObject( obj ) {
    return Object.getOwnPropertyNames(obj).length === 0;
}

This is only a bit faster than is.js though just because you aren't checking whether it is an object.

这个速度比原来快了一点。js只是因为你没有检查它是否是一个对象。

#30


2  

I can't believe after two years of programming js it never clicked that empty objects and array's aren't falsey, the weirdest thing is it never caught me out.

我不相信经过两年的编程js,它从来没有点击过空的对象和数组的不是falsey,最奇怪的是它从来没有被我发现。

this will return true if the input is falsey by default or if it's an empty object or array. the inverse is the trueish function

如果默认输入是falsey,或者是空的对象或数组,这将返回true。逆是trueish函数。

http://codepen.io/synthet1c/pen/pjmoWL

http://codepen.io/synthet1c/pen/pjmoWL

function falsish( obj ){
    if( (typeof obj === 'number' && obj > 0) || obj === true ){
        return false;
    }
    return !!obj
        ? !Object.keys( obj ).length
        : true;
}

function trueish( obj ){
    return !falsish( obj );
}

falsish({})           //=> true
falsish({foo:'bar'})  //=> false
falsish([])           //=> true
falsish(['foo'])      //=> false
falsish(false)        //=> true
falsish(true)         //=> false
// the rest are on codepen