javascript - Empty JS Object - Stack Overflow

Is there a better way to check if an object is empty?I'm using this:function isObjEmpty(obj){for

Is there a better way to check if an object is empty? I'm using this:

function isObjEmpty(obj)
{
    for (var p in obj) return false;
    return true;
}

Is there a better way to check if an object is empty? I'm using this:

function isObjEmpty(obj)
{
    for (var p in obj) return false;
    return true;
}
Share Improve this question edited May 7, 2012 at 13:52 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked May 7, 2012 at 13:34 Rodrigo ManguinhoRodrigo Manguinho 1,4113 gold badges21 silver badges28 bronze badges 4
  • 1 What do you consider "empty"? – Niko Commented May 7, 2012 at 13:36
  • Why to use hasOwnProperty => ref: jsfiddle/v3Lyn – Yoshi Commented May 7, 2012 at 13:38
  • This question has nothing to do with JSON. – Felix Kling Commented May 7, 2012 at 13:51
  • possible duplicate of How do I test for an empty Javascript object from JSON? – Felix Kling Commented May 7, 2012 at 13:52
Add a ment  | 

3 Answers 3

Reset to default 10

If you're looking for a one-liner, consider Object.keys:

var isEmpty = !Object.keys(obj).length;

Your current method is dangerous, since it will always return false when Object.prototype has been extended: http://jsfiddle/Neppc/

Another option is built into jQuery: jQuery.isEmptyObject(obj)

Edit: Interestingly, that implementation is the same as your code in the question.

Actually this is a very good way to check if an object is empty! And it is 10 times faster for exmpty objects than using Object.keys() as suggested above :)

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

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744958230a4603327.html

相关推荐

  • javascript - Empty JS Object - Stack Overflow

    Is there a better way to check if an object is empty?I'm using this:function isObjEmpty(obj){for

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信