如何将变量传递给 javascript 中的过滤器函数?
在这种情况下,我试图将一个值传递给变量“maxage”:
var dateFilter = function(value,maxage) { // Age in miliseconds
if(Date.now() - value < maxage) {
return value;
} else {
return false;
}
}
dates.filter(dateFilter,500);
如何将值 500
作为 maxage
传递给过滤器?
最佳答案
您需要调用 Function.prototype.bind
来创建类似于默认参数的内容。
dates.filter(dateFilter.bind( null, 500 ));
dateFilter
回调将被调用 500
PLUS "automatic passed in values"value, index, array
.
function dateFilter( customArgument, value, index, array ) {
// customArgument === 500
}
关于javascript - 将值传递给 javascript 数组过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755718/