【问题标题】:How is this statement a Boolean这个语句如何是布尔值
【发布时间】:2017-01-31 01:24:18
【问题描述】:

我正在阅读 Eloquent JS 和关于高阶函数的章节,我无法理解这段代码。

function noisy (f) {
  return function (arg) {
    console.log ("calling with" , arg ) ;
    var val = f(arg);
    console.log ("called with" ,arg, "- got",val) ;
    console.log(typeof f(arg))
    return val ;
};
}
noisy (Boolean)(0) ;
  • 第 4 行如何是布尔语句?
  • 这个语句中的 f 是做什么用的?

【问题讨论】:

    标签: javascript function boolean


    【解决方案1】:
    • 因为在内部函数内部,typeof f(arg) 被称为typeof Boolean(0)
    • f0,它被传递给 Boolean 构造函数。

    【讨论】:

      【解决方案2】:

      noisy(f) 这是一个返回函数的函数。

      noisy(Boolean)返回函数:

      function returned(arg) {
          console.log("calling with", arg);
          var val = Boolean(arg);
          console.log("called with", arg, "- got", val);
          console.log(typeof Boolean(arg));
          return val;
      };
      

      然后调用返回的函数,传入零。所以你实际上是在执行以下代码:

      console.log("calling with", 0);
      var val = Boolean(0);
      console.log("called with", 0, "- got", val);
      console.log(typeof Boolean(0));
      

      回答你的问题:

      • 第 4 行是一个布尔表达式,因为您传入了一个类型并调用了它的构造函数
      • f 是由噪声定义的变量,被捕获以在噪声返回的函数中使用

      【讨论】:

      • 谢谢这是一个很好的解释,我很感激
      • 很高兴它有帮助。如果您可以将答案标记为已回答,我将不胜感激,这样我就可以获得一些 StackOverflow 声誉 =)
      猜你喜欢
      • 2013-03-03
      • 2021-12-07
      • 2019-10-04
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      相关资源
      最近更新 更多