【问题标题】:Empty Object in CoffeescriptCoffeescript 中的空对象
【发布时间】:2014-06-02 02:04:20
【问题描述】:

我想做一个 if 语句来检查一个对象是否为空对象。

我所说的空对象是指如果我执行 console.log(object) 它会打印出 {}。

我该怎么做?

【问题讨论】:

标签: coffeescript


【解决方案1】:
myObject = {}
if Object.keys(myObject).length == 0
    # myObject is "empty"
else
    # myObject is not "empty"

【讨论】:

  • Object.keys 是 ES5,不能在 IE
【解决方案2】:

这个功能可能对你有用:

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

【讨论】:

  • 小心{foo: undefined} 对象将返回true,而不是您可能期望的false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 2020-08-12
  • 2012-06-20
相关资源
最近更新 更多