检查数组是否在coffeescript中有一些项目

mir*_*lon 13 arrays coffeescript

coffeescript中是否有一些方法在数组中包含一些项时返回true?像ruby中的方法一样present?:

[].present? false
[1].present? true
Run Code Online (Sandbox Code Playgroud)

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

alert("Empty Array")  unless [].length
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎很蹩脚.

Jiř*_*šil 23

我不认为有但可以:

Array::present = ->
  @.length > 0

if [42].present()
  # why yes of course
else
  # oh noes
Run Code Online (Sandbox Code Playgroud)

一个非常简单和不完整的实现,但它应该给你一些想法.而对于记录,present?Ruby中没有方法,该方法由active_supportgem 添加.

  • 为清楚起见,我会选择`empty()`(就像Ruby中的`empty?`).稍微不那么可疑的恕我直言. (3认同)

Mic*_*ník 6

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