Checking Function inside IF 语句说明

Checking Function inside IF statement explanation

我正在声明一个用作比较的函数。我的问题是:

为什么条件充当语句?

为什么第 4 行有效而第 5 行无效?

我知道这段代码不切实际且未被使用,但为什么编译器允许这种语法?

google 上没有答案。不过话又说回来,我可能没找对地方。

var A = () => console.log(3);

if (A === console.log(1)) {
  A();
};

A ? A() : null;

if (A === console.log(1567)) {};

if (B === console.log(1567)) {};

预期输出为:

3

输出为:

1

3

1567

Uncaught ReferenceError: B is not defined at :11:1

表达式 console.log(1) 的计算结果为 undefinedA 不是 undefined,所以 none 的比较是正确的。

但是在返回 undefined 之前,console.log(1)1 打印到控制台。因此,您示例中的第一行和第三行输出来自 console.log(1)console.log(1567).

的评估

console.log(1) 不是闭包。闭包是 ()=>console.log.

一行一行的意思 -

  1. 第一行将 A 定义为箭头函数。
  2. 下一行比较 - 从右到左 - A 已定义并具有一些值,下一个 console.log(1) 是一个函数调用,因此它的值为 "evaluated"。并将 return 值与 A 的定义值进行比较 - 结果是错误的(A 是函数引用,而 console.log() returns undefined).
  3. 如果 - offcourse A 被定义所以它调用 A() - 因此第二行输出。
  4. 再次比较——类似点(2)
  5. 再次比较 - 但 B 未定义,它是可抛出的,因此错误并从左到右 - console.log 从未被评估。

问题 -

  1. 条件充当语句 - 它是设计使然 - 尝试 if(console.log()) - 它们是代码评估为 true/false 执行方向的地方。在那个区域有一个声明提供了像 - while(true){}while(someFuncIfTrue(2)){}.
  2. 这样的功能
  3. 第 4 步有效但第 5 步无效 - 第 (5) 点回答了这个问题。