首页 > 解决方案 > 如果 console.log(x) 正在注销,为什么这会同时注销?

问题描述

我得到了这两个输出,但我不知道为什么

var sample = (x) =>  console.log(x) || x.slice(1); 
console.log(sample('jeff'));
// why does this log out both if console.log(x) is logging out?
// jeff
// eff

标签: javascript

解决方案


为了解释你的函数中发生了什么,当你将值'jeff'传递给你的函数调用时,它会评估表达式console.log(x) || x.slice(1),它首先记录"jeff"并因为console.log()返回undefined,然后x.slice()执行返回"eff"。并且因为您已经将您的函数调用包装在另一个中console.log(),所以它最终将返回值“eff”记录到控制台。

因此将两个值记录到控制台。

为了澄清尝试使用浏览器中的开发工具在控制台中执行此操作

 console.log("hello") || console.log("hey")

 // expected result two logs in console "hello" and "hey"

现在尝试在控制台中执行这个

 console.log("hello") && console.log("hey")

 // expected result only one log in console "hello"

在第二种情况下,会发生这种情况,因为 firstconsole.log被调用,它将“hello”记录到控制台并返回undefined,并且因为 undefined 是假的,所以第二个console.log永远不会被调用。


推荐阅读