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