通过函数过滤
重要性:5
数组有一个内置方法 arr.filter(f)。它通过函数 f 过滤所有元素。如果它返回 true,则该元素将被返回到结果数组中。
创建一组“可立即使用”的过滤器
inBetween(a, b)– 在a和b之间,或等于它们(包含)。inArray([...])– 在给定的数组中。
用法必须像这样
arr.filter(inBetween(3,6))– 只选择 3 到 6 之间的值。arr.filter(inArray([1,2,3]))– 只选择与[1,2,3]中的成员之一匹配的元素。
例如
/* .. your code for inBetween and inArray */
let arr = [1, 2, 3, 4, 5, 6, 7];
alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
alert( arr.filter(inArray([1, 2, 10])) ); // 1,2
过滤 inBetween
function inBetween(a, b) {
return function(x) {
return x >= a && x <= b;
};
}
let arr = [1, 2, 3, 4, 5, 6, 7];
alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
过滤 inArray
function inArray(arr) {
return function(x) {
return arr.includes(x);
};
}
let arr = [1, 2, 3, 4, 5, 6, 7];
alert( arr.filter(inArray([1, 2, 10])) ); // 1,2