CoffeeScript攻略4.9:篩選陣列
問題
你想要根據布林條件來篩選陣列。
方案
使用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方法類似。
相關文章
- CoffeeScript攻略4.8:歸納陣列陣列
- CoffeeScript攻略4.7:對映陣列陣列
- CoffeeScript攻略4.10:反轉陣列陣列
- CoffeeScript攻略4.1:從陣列生成字串陣列字串
- CoffeeScript攻略4.6:打亂陣列元素陣列
- CoffeeScript攻略4.3:取得陣列最大值陣列
- CoffeeScript攻略4.4:使用陣列交換變數陣列變數
- CoffeeScript攻略4.5:定義陣列範圍陣列
- 陣列多重篩選條件排序方法陣列排序
- JS中的陣列過濾,從簡單篩選到多條件篩選JS陣列
- 使用jquery篩選和過濾陣列程式碼例項jQuery陣列
- CoffeeScript攻略1.1:嵌入JavaScriptJavaScript
- CoffeeScript攻略1.3:for迴圈
- CoffeeScript攻略3.7:拆分字串字串
- CoffeeScript攻略3.9:匹配字串字串
- 篩選出陣列中屬性為true的每條資料陣列
- CoffeeScript攻略3.8:字串插值字串
- CoffeeScript攻略3.1:重複字串字串
- Pandas根據篩選條件對指定excel列進行篩選!神器!Excel
- CoffeeScript攻略3.4:查詢子字串字串
- CoffeeScript攻略1.2:比較範圍
- CoffeeScript攻略2.4:建立類變數變數
- CoffeeScript攻略2.5:鏈式呼叫物件物件
- CoffeeScript攻略3.10:生成唯一ID
- CoffeeScript攻略2.1:克隆物件(深複製)物件
- 陣列選擇排序陣列排序
- CoffeeScript攻略2.3:CoffeeScrip的type函式函式
- jquery篩選陣列之grep、each、inArray、map的用法及遍歷json物件 [轉]jQuery陣列JSON物件
- CoffeeScript攻略3.6:大寫單詞首字母
- Android開商品屬性篩選與商品篩選Android
- CoffeeScript攻略4.2:類似Python的zip函式Python函式
- CoffeeScript攻略3.2:把字串轉換為小寫形式字串
- CoffeeScript攻略3.3:把字串轉換為大寫形式字串
- CoffeeScript攻略3.5:清理字串前後的空白符字串
- jQuery 篩選方法jQuery
- 動態篩選
- 直接拿來用!超實用的Java陣列技巧攻略Java陣列
- JQuery選擇器——可見性篩選選擇器和屬性篩選選擇器jQuery