2011-05-20 70 views
38

從節點REPL的東西,如何匹配Javascript中的空字典?

> d = {} 
{} 
> d === {} 
false 
> d == {} 
false 

假設我有一個空的字典,我如何確保它是一個空的字典?

+1

你可能會考慮使用一個庫,例如[check-types](https://www.npmjs.com/package/check-types)。在這種情況下,你可以使用'check.emptyObject(d)'。 – mareoraft 2015-10-29 00:36:27

回答

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

僅適用於較新的瀏覽器。爲了記錄,keys屬性僅在IE> = 9 [參考](http://kangax.github.io/compat-table/es5/) – 2014-12-09 04:52:57

10

由於它沒有屬性,for循環將沒有任何東西可以迭代。爲了在應有的地方給予獎勵,我發現這個建議here

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

isEmpty({a:1}) // false 
isEmpty({}) // true 
+1

我會創建一個count(obj)函數,如果count等於0,isEmpty會被評估。 – 2011-05-20 13:34:30

+5

您可能想在返回false之前檢查'obj.hasOwnProperty(i)'。這會過濾掉通過原型鏈繼承的屬性。 – 2011-05-20 13:36:38

1

你得檢查,這是類型的「對象」的,像這樣:

(typeof(d) === 'object')

,然後實現短的「大小」功能來檢查它是空的,as mentioned here

19

你可以用這種方法isEmpty擴展Object.prototype檢查對象是否已經沒有自己的屬性:

Object.prototype.isEmpty = function() { 
    for (var prop in this) if (this.hasOwnProperty(prop)) return false; 
    return true; 
}; 
+17

Wow ..中支持。我覺得JavaScript很有趣,它缺少這種「基本」功能 – harijay 2011-10-12 22:28:57

+1

擴展Object.prototype可能會產生迭代對象的問題http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ – 2014-06-12 14:22:19

+0

這干擾了jquery – 2014-12-24 10:14:06

0

如果您試穿一下Node.js的使用這個片段,在此基礎上的代碼here

Object.defineProperty(Object.prototype, "isEmpty", { 
    enumerable: false, 
    value: function() { 
      for (var prop in this) if (this.hasOwnProperty(prop)) return false; 
      return true; 
     } 
    } 
); 
8

這就是jQuery使用,工作得很好。雖然這確實需要jQuery腳本使用isEmptyObject

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

//Example 
var temp = {}; 
$.isEmptyObject(temp); // returns True 
temp ['a'] = 'some data'; 
$.isEmptyObject(temp); // returns False 

如果包含jQuery不是一個選項,只需創建一個單獨的純javascript函數。

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

//Example 
var temp = {}; 
isEmptyObject(temp); // returns True 
temp ['b'] = 'some data'; 
isEmptyObject(temp); // returns False 
9

如何使用jQuery?

$.isEmptyObject(d) 
2

我遠離JavaScript學者,但做了以下工作嗎?

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

它具有作爲單線純函數調用的優點。

+0

很酷的解決方案!它實際上是唯一沒有循環且沒有調用第三方庫的程序 – 2015-12-27 13:18:25

1
var SomeDictionary = {}; 
if(jQuery.isEmptyObject(SomeDictionary)) 
// Write some code for dictionary is empty condition 
else 
// Write some code for dictionary not empty condition 

這工作正常。

0

如果性能是不是一個考慮因素,這是一個簡單的方法,很容易記住:

JSON.stringify(obj) === '{}' 

顯然,你不想成爲一個循環字符串化大型對象,雖然。