JS使用部分参数化的功能 [英] JS using partially parametrized function

查看:136
本文介绍了JS使用部分参数化的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手,我尝试过以下代码:

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)

我认为它不起作用,因为prototype(在Array.prototype.filter()中)不包含阈值,因此它是类型不匹配的,但是我们不能这样定义: isBiggerThenZero = 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, 2, 3].every(isBigEnough(0))时.它:

  • 调用返回falseisBigEnough.
  • 执行[1, 2, 3].every(false).其中false不是函数.所以它给你一个错误.
  • 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))

这篇关于JS使用部分参数化的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆