CoffeeScript攻略4.9:篩選陣列

CoffeeScript Cookbook發表於2011-12-09

問題

你想要根據布林條件來篩選陣列。

方案

使用Array.filter (ECMAScript 5): array = [1..10]

array.filter (x) -> x > 5
# => [6,7,8,9,10]

在EC5之前的實現中,可以擴充套件Array的原型新增一個篩選函式,該函式接受一個回撥並對自身進行過濾,將回撥函式返回true的元素收集起來。

# 擴充套件Array的原型
Array::filter = (callback) ->
  element for element in this when callback(element)

array = [1..10]

# 篩選偶數
filtered_array = array.filter (x) -> x % 2 == 0
# => [2,4,6,8,10]

# 過濾掉小於或等於5的元素
gt_five = (x) -> x > 5
filtered_array = array.filter gt_five
# => [6,7,8,9,10]

討論

這個方法與Ruby的Array#select方法類似。


enter image description here

相關文章