JavaScript filter() 示例
JS 查找所有以 substring 开头的名字
检查数组中的每个字符串,如果它以“test”开头,则将其丢弃。
const names = ["JackLi", "BobRobert", "testName", "Lucie", "testD"]; const validNames = names.filter(str => !str.toLowerCase().startsWith("test")); console.log(validNames); //Prints ["JackLi", "BobRobert", "Lucie"]
JS 过滤对象数组
找出salary大于5000的对象
const employees = [ {id: 1, name: "JackLi", salary: 4000}, {id: 2, name: "BobRobert", salary: 5000}, {id: 3, name: "Lucie", salary: 6000}, {id: 4, name: "Tomm", salary: 7000}, {id: 5, name: "emily", salary: 2000} ]; const selectedEmployees = employees.filter(e => e.salary > 5000); console.log(selectedEmployees);
JS Array.prototype.filter() 示例
const doirts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = doirts.filter(d => d > 7); console.log(result); //Prints [8, 9]
在上面的例子中,我们有一个从 0 到 9 的整数数组。
我们想要获取所有大于 7 的整数。
在上面的 filter()
示例中,我们指定了一个谓词,它是匿名函数并且只返回布尔结果。
为了使示例更清晰,我们可以在没有谓词和 lambda 表达式的情况下重写上面的示例。
const doirts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = doirts.filter(isGreaterThanSeven); console.log(result); //Prints [8, 9] function isGreaterThanSeven(d) { if(d > 7) return true; else return false; }
JavaScript Array filter() 方法接受一个数组和一个回调函数作为参数,并返回一个新数组,其中包含所有通过给定回调函数定义的测试的元素。
- 在内部,
filter()
方法迭代原始数组的每个元素并将每个元素传递给回调函数。如果回调函数返回true
,则该元素包含在新的返回数组中。 - 新数组将是原始数组的子集。
filter()
操作不会修改原始数组。- 因为
filter()
方法返回一个新数组,我们可以将过滤器结果与其他迭代方法链接起来,例如sort()
和map()
。
https://onitroad.com 更多教程
JS filter 回调函数
filter()
操作中使用的回调函数的每次调用都接受三个参数:
- 原始数组中的元素(必填)
- 元素的索引(可选)
- 对正在遍历的原始数组的引用(可选)
让我们再重写一次上面的例子,以便更清楚地理解 filter()
操作。
const doirts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = doirts.filter(isGreaterThanSeven); console.log("Filtered array is : " + result); function isGreaterThanSeven(d, i, arr) { console.log("The array inside callback function is : " + arr); if(d > 7) { console.log("Selected element value is : " + d); console.log("Selected element index is : " + i); return true; } else { return false; } }
输出:
The array inside callback function is : 0,1,2,3,4,5,6,7,8,9 //Printed 9 times (for each element from 0 to 8) Selected element value is: 8 Selected element index is: 8 The array inside callback function is : 0,1,2,3,4,5,6,7,8,9 Selected element value is: 9 Selected element index is: 9 Filtered array is : [8,9]
日期:2020-09-17 00:10:39 来源:oir作者:oir