【问题标题】:Checking Function inside IF statement explanationChecking Function inside IF 语句说明
【发布时间】:2019-09-06 04:45:48
【问题描述】:
我声明了一个用作比较的函数。我的问题是:
为什么条件充当语句?
为什么第 4 行有效,但第 5 行无效?
我知道这段代码不切实际且未使用,但为什么编译器允许这种语法?
谷歌上没有答案。不过话说回来,我可能没找对地方。
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
【问题讨论】:
标签:
javascript
function
if-statement
equality
【解决方案1】:
一行一行的意思——
- 第一行将
A 定义为箭头函数。
- 下一行比较 - 从右到左 -
A 已定义并具有一些值,下一个 console.log(1) 是一个函数调用,因此它的值是“评估的”。并将返回值与 A 的定义值进行比较 - 结果是错误的(A 是函数引用,而 console.log() 返回 undefined)。
- Out of if - offcourse
A 已定义,因此它调用 A() - 因此是第二行输出。
- 再次比较——类似于第(2)点
- 再次比较 - 但
B 未定义,它是可抛出的,因此错误并从左到右 - 永远不会评估 console.log。
问题 -
- Condition 充当语句 - 这是设计使然 - 尝试
if(console.log()) - 如果评估为真/假,则它们是代码执行方向的地方。并且在该区域发表声明提供了类似的功能 - while(true){} 或 while(someFuncIfTrue(2)){}。
- 第 4 步有效,但第 5 点无效 - point(5) 回答了这个问题。
【解决方案2】:
表达式console.log(1) 的计算结果为undefined。 A 不是 undefined 所以没有一个比较是真的。
但是,在返回 undefined 之前,console.log(1) 会将 1 打印到控制台。因此,您示例中输出的第一行和第三行来自对 console.log(1) 和 console.log(1567) 的评估。
console.log(1) 不是闭包。关闭是()=>console.log。