一、作用
filter用於對數組進行過濾。
它創建一個新數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
注意:filter()不會對空數組進行檢測、不會改變原始數組
二、語法
Array.filter(function(currentValue, indedx, arr), thisValue)
其中,函數 function 為必須,數組中的每個元素都會執行這個函數。且如果返回值為 true,則該元素被保留;
函數的第一個參數 currentValue 也為必須,代表當前元素的值。
三、實例
返回數組nums中所有大於5的元素。
1 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 2
3 let res = nums.filter((num) => { 4 return num > 5; 5 }); 6
7 console.log(res); // [6, 7, 8, 9, 10]