filter()
方法是 JavaScript 中的一个内置函数,可以用于从数组中筛选出符合特定条件的元素,返回一个新的数组。
filter()
方法接受一个回调函数作为参数,该回调函数会遍历数组中的每一个元素并返回一个布尔值。如果回调函数返回 true
,则该元素将被包含在新的数组中;如果回调函数返回 false
,则该元素将被过滤掉。
例如,以下代码将从数组 numbers
中筛选出所有大于 3 的元素:
const numbers = [1, 2, 3, 4, 5]; const filteredNumbers = numbers.filter(num => num > 3); console.log(filteredNumbers); // [4, 5]
可以看到,filter()
方法返回了一个新的数组 filteredNumbers
,其中包含了原数组 numbers
中所有大于 3 的元素。
如果出现Uncaught TypeError: item.xxx.includes is not a function报错
这个错误提示是因为includes()
方法只能在字符串和数组上调用,而item.age
可能不是一个字符串或数组类型。
解决方法有两种:
将item.age
转为字符串类型,然后再调用includes()
方法:
if (item.xxx.toString().includes(inputVal)) { // ... }
使用===
运算符来比较item.age
和inputVal
是否相等:
if (item.xxx=== inputVal) { // ... }