Coffeescript中的空对象

foo*_*ill 13 coffeescript

我想创建一个if语句来检查对象是否是一个空对象.

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

我该怎么做呢?

go-*_*leg 19

myObject = {}
if Object.keys(myObject).length == 0
    # myObject is "empty"
else
    # myObject is not "empty"
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)