2013-07-08 17 views
10

Chcę utworzyć instrukcję if, aby sprawdzić, czy obiekt jest pusty, czy nie.Pusty obiekt w Coffeescript

Przez pusty obiekt mam na myśli, jeśli zrobię console.log (obiekt), wydrukuje {}.

Jak to zrobić?

+1

możliwe duplikat [? Czy obiekt pusty] (http://stackoverflow.com/questions/4994201/is-object-empty) – Blender

Odpowiedz

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

Object .keys to ES5 i nie będzie działać na IE <9 (Naprawiono przy użyciu ES5Shim) –

5

Funkcja ta może pracować dla Ciebie:

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 
+1

Ostrożnie obiekt '{foo: undefined}' zwróci 'true', a nie' false' jak można się spodziewać. – Cimm