拆分过滤器回调函数

split filter callback function out

本文关键字:函数 回调 过滤器 拆分      更新时间:2023-09-26
arr.filter(filterCallback(this, newValue));
function filterCallback(this, newValue){
   return this !== newValue;
}

上面的代码不工作,不知道哪里出错了。这是工作之前,我试图拆分函数。

arr.filter(function(val){
    return val !== newValue;
});

您可以使用Function.prototype.bind()带参数调用filterCallback,并接收.filter()callback的电流元素进行值比较。您也可以将filterCallback()this设置为传递给.bind()的第一个参数

var arr = [1,2,3];
var not = {n:3};
var res = arr.filter(filterCallback.bind(not));
function filterCallback(el){
    return this.n !== el;
}
console.log(res); // [1, 2]

可以:-

arr.filter(filterCallback);
function filterCallback(){
   return newValue;
}

检查片段

var ages = [32, 33, 16, 40];
function checkAdult(age) {
    return age >= 18;
}
function myFunction() {
    document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
<p>Click the button to get every element in the array that has a value of 18 or more.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>