JS之filter()方法的使用


一、作用

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]

原文:https://www.jianshu.com/p/494226d9dd2c


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM