最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Empty JS Object - Stack Overflow

programmeradmin5浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论