2013-07-08 38 views
10

我想做一個if語句來檢查對象是否爲空對象。Coffeescript中的空對象

通過空對象我的意思是如果我做console.log(對象)它打印出{}。

我該怎麼做?

+1

可能重複(http://stackoverflow.com/questions/4994201/is-object-empty) – Blender

回答

17
myObject = {} 
if Object.keys(myObject).length == 0 
    # myObject is "empty" 
else 
    # myObject is not "empty" 
+1

對象.keys是ES5,不適用於IE <9(使用ES5Shim修復) –

5

該功能可能會爲你工作:

is_empty = (obj) -> 
    return true if not obj? or obj.length is 0 

    return false if obj.length? and obj.length > 0 

    for key of obj 
     return false if Object.prototype.hasOwnProperty.call(obj,key) 

    return true 

#Examples 
console.log is_empty("") #true 
console.log is_empty([]) #true 
console.log is_empty({}) #true 
console.log is_empty(length: 0, custom_property: []) #true 

console.log is_empty("Hello") #false 
console.log is_empty([1,2,3]) #false 
console.log is_empty({foo: 1}) #false 
console.log is_empty(length: 3, custom_property: [1,2,3]) #false 
的[?是Object空]
+1

小心對象'{foo:undefined}'會返回true,而不是像您所期望的那樣返回false。 – Cimm