Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - 如何测试一个空的JavaScript对象?(How do I test for an empty JavaScript object?)

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?

(如何检查情况呢?)

  ask by falmp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ECMA 7+ :

(ECMA 7+ :)

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

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:

(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

(ek)

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

ExtJS

(ExtJS)

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

AngularJS (version 1)

(AngularJS(版本1))

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

Ramda

(拉姆达)

R.isEmpty({}); // true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...