iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
0
自我挑戰組

JavaScript Array x 學習筆記系列 第 15

[Day 15 | Array.prototype.filter () ]

array.filter()

filter 像是過濾,

經過迭代過濾完資料後 filter 會回傳一個新的陣列

不會影響到原來的陣列資料。

哈! 每次都寫的很簡短

看看MDN怎麼解釋好了!

MDN >> filter() 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。


Syntax (From MDN)

newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
  • callback
    此函式為一個斷言,用於測試陣列中的每個元素。回傳值為 true 時將當前的元素保留至新陣列中,若為 false 則不保留。可傳入三個參數:

  • element
    原陣列目前所迭代處理中的元素。

  • index(選擇性)
    原陣列目前所迭代處理中的元素之索引。

  • array(選擇性)
    呼叫 filter 方法的陣列。


Example

使用filter 找出陣列資料大於8個字的資料


程式碼如下:

const product = ['i-7561', 'wise-5231', 'wise-5800', 'wise-7201', 'MQ-7244', 'MQ-7251', 'PET-7H16M', 'PET-7H24M'];

const result = product.filter(item => item.length > 8)

console.log(result);

Example2

簡易搜尋

這個範例複習到前幾天我們學到的indexOf如果有找到符合的資料,回傳該值第一次找到的位置,如果沒有則是回傳 -1, 依照這個範例,filter 的條件是大於 -1,也就是說只會回傳有符合'wise'字串的陣列資料。

程式碼如下:

const product = ['i-7561', 'wise-5231', 'wise-5800', 'wise-7201', 'MQ-7244', 'MQ-7251', 'PET-7H16M', 'PET-7H24M'];

let filter = product.filter(function(item){
  
  return item.indexOf('wise') > -1; 
  
}) 
console.log(filter)


上一篇
[Day 14 | Array.prototype.lastIndexOf () ]
下一篇
[Day 16 | Array.prototype.find () ]
系列文
JavaScript Array x 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言