检查如果一个数组中的CoffeeScript一些项目(Checking if an array ha

2019-07-18 02:47发布

是否有一些的CoffeeScript方法时,一个数组中有一些项目,则返回true? 像红宝石方法present?

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

根据http://arcturo.github.com/library/coffeescript/07_the_bad_parts.html中的CoffeeScript阵列空虚由其长度来确定

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

这似乎很跛脚我。

Answer 1:

我不认为有,但可以是:

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

if [42].present()
  # why yes of course
else
  # oh noes

一个非常简单的和不完整的实现,但它应该给你一些想法。 并记录在案,有没有present? 在红宝石方法,该方法是由加入active_support宝石。



Answer 2:

不幸的是,没有。 做到这一点的最好办法是通过比较它的长度。



Answer 3:

我想使用in作品也是如此。

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

Output
$ present


文章来源: Checking if an array has some items in coffeescript