Javascript 如何将变量值传递给.filter()
以下代码取自参考文件: 我想知道是否可以通过传入变量动态更改Javascript 如何将变量值传递给.filter(),javascript,Javascript,以下代码取自参考文件: 我想知道是否可以通过传入变量动态更改return行中10的值。从参考资料中我想不出怎么做。我想调用相同的过滤器回调,但为正则表达式测试传入一个唯一的值 所以它看起来像: function isBigEnough(value, num) { return value >= num; } 试试这个 function isBigEnough(num) { return function(value) { return value >
return
行中10
的值。从参考资料中我想不出怎么做。我想调用相同的过滤器回调,但为正则表达式测试传入一个唯一的值
所以它看起来像:
function isBigEnough(value, num) {
return value >= num;
}
试试这个
function isBigEnough(num) {
return function(value) {
return value >= num;
}
}
然后
[12, 5, 8, 130, 44].filter(isBigEnough(10));
这是怎么回事
- 调用
返回一个匿名函数isbigtough(10)
- 然后,该匿名函数被传递给过滤器
10
)作为this
传递
function isBigEnough(value) {
return value >= this;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough, 10);
最简单的方法是使用匿名函数并关闭要使用的变量:
var minSize = 10;
var filtered = [12, 5, 8, 130, 44].filter( val => val >= minSize );
如果您确实希望保留一个要回调的命名函数,可以使用bind部分应用一个参数:
function isBigEnough(minSize, value) {
return value >= minSize;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough.bind(null,10));
在这里,bind将返回一个新函数,其中最左边的参数绑定为10(第一个参数为null,是调用时作为this
传递给函数的参数)。因此筛选器传入的参数将显示为回调中的第二个值。这种(更通用的)方法如何:
//argument order is chosen to be consistent through all functions, and readability when used:
var op = { //for operator
eq: b => a => a === b, //equal
neq: b => a => a !== b, //not equal,
gt: b => a => a > b, //greater than
lt: b => a => a < b, //lower than
gteq: b => a => a >= b,
lteq: b => a => a <= b,
//bonus, negating a function:
not: fn => (...args) => !fn(...args) //to be used as `arr.filter( op.not(filterFn) )`
}
您可以使用
bind
对函数进行curry处理或部分应用它,比如.filter(isbigtough.bind(null,num))
,只需翻转参数即可。尽管这样做有效,但其他答案可能更合适。对不起,我甚至无法让它起作用。谢谢你,我不知道为什么。这是一个工作,我喜欢这样,但如何通过这样的正则表达式。。。(我得到一个未定义val
的错误):var filtered=words.filter(/\b\w{5}[.]/.test(val))
您错过了开头的箭头(这是一种ES6匿名函数):var filtered=words.filter(val=>/\b\w{5}[.]/.test(val))
@MichaelRader或等效的(在本例中)ES5和以前的版本:var filtered=words.filter(函数(val){return/\b\w{5}[.]/.test(val);})
//argument order is chosen to be consistent through all functions, and readability when used:
var op = { //for operator
eq: b => a => a === b, //equal
neq: b => a => a !== b, //not equal,
gt: b => a => a > b, //greater than
lt: b => a => a < b, //lower than
gteq: b => a => a >= b,
lteq: b => a => a <= b,
//bonus, negating a function:
not: fn => (...args) => !fn(...args) //to be used as `arr.filter( op.not(filterFn) )`
}
var filtered = [12, 5, 8, 130, 44].filter( op.gteq(10) );
//or:
//defining how to validate thew values
var isBigEnough = op.gteq(10);
//...
//the rest of the code only utilizes this function -> only 1 place to change
var filtered = [12, 5, 8, 130, 44].filter( isBigEnough );