JS using partially parametrized function

[亡魂溺海] 提交于 2020-01-17 07:30:38

问题


I'm very new to JS, I've tried code below :

function isBigEnough(element, index, array, threshold) {
  return (element >= threshold);
}
[1, 2, 3].every(isBigEnough(threshold=0)

I thought it doesn't work because prototype (in Array.prototype.filter()) does not contain threshold, so it is types mismatch, but we can't define like this : isBiggerThenZero = isBigEnough(threshold=0) so is there nice workaround for this case ?


回答1:


When you do [1, 2, 3].every(isBigEnough(0)). It:

  • Calls isBigEnough that returns false.
  • Executes [1, 2, 3].every(false). Where false is not a function. SO it gives you an error.

You can use a closure that binds threshold value to the returned function:

function isBigEnough(threshold) {
  return function(element, index, array) {
     return (element >= threshold);
  }
}
[1, 2, 3].every(isBigEnough(0))



回答2:


Default parameters must be in the function declaration, e.g:

function isBigEnough(element, index, array, threshold=0) {
  return (element >= threshold);
}
[1, 2, 3].every(isBigEnough);

However, now its difficult to pass threshold:

[1,2,3].every((...a)=>isBigEnough(...a,2));

So you could rather do:

function isBigEnough(threshold=0,element, index, array) {
 return (element >= threshold);
}
[1, 2, 3].every(isBigEnough.bind(null,5));//threshold=5


来源:https://stackoverflow.com/questions/44718965/js-using-partially-parametrized-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!