一收叶、作用
filter用于對數(shù)組進行過濾骄呼。
它創(chuàng)建一個新數(shù)組,新數(shù)組中的元素是通過檢查指定數(shù)組中符合條件的所有元素。
注意:filter()不會對空數(shù)組進行檢測谒麦、不會改變原始數(shù)組
二俄讹、語法
Array.filter(function(currentValue, indedx, arr), thisValue)
??其中哆致,函數(shù) function 為必須绕德,數(shù)組中的每個元素都會執(zhí)行這個函數(shù)。且如果返回值為 true摊阀,則該元素被保留耻蛇;
??函數(shù)的第一個參數(shù) currentValue 也為必須,代表當前元素的值胞此。
三臣咖、實例
返回數(shù)組nums中所有大于5的元素。
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
return num > 5;
});
console.log(res); // [6, 7, 8, 9, 10]