【问题标题】:Checking if an array has some items in coffeescript检查数组中是否有咖啡脚本中的某些项目
【发布时间】:2012-12-26 02:02:34
【问题描述】:

当数组中有一些项目时,coffeescript 中是否有一些方法返回 true? ruby中的like方法present?:

[].present? false
[1].present? true

根据http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html,coffeescript 中的数组是否为空是由它的长度决定的

alert("Empty Array")  unless [].length

这对我来说似乎很蹩脚。

【问题讨论】:

    标签: arrays coffeescript


    【解决方案1】:

    我认为没有但可以:

    Array::present = ->
      @.length > 0
    
    if [42].present()
      # why yes of course
    else
      # oh noes
    

    一个非常简单和不完整的实现,但它应该给你一些想法。并且记录一下,Ruby 中没有present? 方法,该方法是由active_support gem 添加的。

    【讨论】:

    • 为了清楚起见,我会选择empty()(就像Ruby中的empty?)。恕我直言,不太可疑。
    • @Cimm 我认为两者都是 Ruby 的 Array 类中的方法,并且在我所见的情况下都很常见。
    【解决方案2】:

    不幸的是,没有。最好的方法是比较它的长度。

    【讨论】:

      【解决方案3】:

      我认为使用in 也可以。

      arr = [1, 2, 3, 4, 5]
      a = 1
      if a in arr
        console.log 'present'
      else
        console.log 'not present'
      
      Output
      $ present
      

      【讨论】:

      • 我认为你没有理解这个问题。
      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      相关资源
      最近更新 更多