javascript - 如果 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
解决方案
为了解释你的函数中发生了什么,当你将值'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
永远不会被调用。
推荐阅读
- angular - 登录服务问题 - Angular 6
- output - Snakemake:尝试生成多个输出文件时出错
- c# - 为什么 automapper 不处理没有 .ForMember 的嵌套对象?
- android - 如何禁用默认来电/短信通知?
- kubernetes - 主节点中的 kubelet 和 dockerd 进程使用太多内存
- python - 在Python中存储位图中黑色像素的(x,y)坐标
- javascript - 如何在 React 中获取当前的 onChange 值?
- php - 如何防止对象泄露有关其自身的所有信息?(就像C的朋友)
- asp.net-mvc - SignalR Clients.Caller(Clients.Caller.GroupName) 不起作用
- php - 使用 static::MY_CONST vs self::MY_CONST vs SomeClass::MY_CONST 引用 PHP 7 中的常量