Javascript 如何知道匹配(50)和匹配(0)的值?

Javascript 如何知道匹配(50)和匹配(0)的值?,javascript,Javascript,我已经在线下载了pdf格式的javascript问答。在测验中得到以下问题,但被输出卡住了 const matched = x => ({ on: () => matched(x), otherwise: () => x, }) const match = x => ({ on: (pred, fn) => (pred(x) ? matched(fn(x)) : match(x)), otherwise: fn => fn(x)

我已经在线下载了pdf格式的javascript问答。在测验中得到以下问题,但被输出卡住了

const matched = x => ({
    on: () => matched(x),
    otherwise: () => x,
})
const match = x => ({
    on: (pred, fn) => (pred(x) ? matched(fn(x)) : match(x)),
    otherwise: fn => fn(x),
})
match(x)
    .on(x => x < 0, () => 0)
    .on(x => x >= 0 && x <= 1, () => 1)
    .otherwise(x => x * 10)
const matched=x=>({
on:()=>匹配(x),
否则:()=>x,
})
常数匹配=x=>({
on:(pred,fn)=>(pred(x)?匹配(fn(x)):匹配(x)),
否则:fn=>fn(x),
})
匹配(x)
.on(x=>x<0,()=>0)
.on(x=>x>=0&&x1)
。否则(x=>x*10)

match(50)和match(0)的值是多少?

我们可以一步一步地调试语句,最终得到预期的结果。但如果我们深入研究逻辑,有一个简单的方法:

  • matched
    将保持输入
    x
    ,无论我们在
    上调用
    多少次,然后在
    上生成输入,否则作为最终结果
  • match
    将首先检查
    pred
    条件
    • 如果它的计算结果为
      true
      ,则它将根据我们在
      上传递给
      fn
      计算结果,并将结果保留在
      匹配的
      对象中
    • 如果
      pred
      的计算结果为
      false
      ,则它不匹配,因此它返回相同的
      match
      对象,等待下一次匹配。如果最后一个中没有匹配项,则将调用传递给
      的函数,否则将调用
      以获得最终结果
基于以上内容,我们注意到,
match
对象将在
事件上的每个
上评估条件,保留第一个
匹配的
结果,最后在
否则
事件上返回它

因此,我们有一些
pred
条件

  • x=>x<0
  • x=>x>=0&&x