全局范围内的console.log(!status)产生意外结果 [英] console.log(!status) in global scope producing unexpected result

查看:73
本文介绍了全局范围内的console.log(!status)产生意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进入一个有趣的问题。我正在努力尝试切换分配给变量的布尔值。它没有用,最终我尝试了这段代码。

Ran into an interesting issue. I was working on trying to toggle a boolean that was assigned to a variable. It wasn't working and eventually I tried this code.

var status = false;
console.log(!status);

我希望它能提供 true 控制台,但我得到 false 。我认为javascript会首先在括号内运行代码以找到它的值,然后在console.log中运行该值。你能解释一下为什么我在控制台中没有得到 true 值吗?

I expected it to provide true in the console, but instead I got false. I figured that javascript would run the code inside the parenthesis first to find it's value and then console.log the value. Could you please explain why I am not getting a true value in the console?

推荐答案

window.status 已经存在(它用于获取/设置浏览器状态栏的文本),当为其分配值时,它将转换为字符串。如果你执行 console.log(status); ,你会看到 status 的字符串值false,这会导致您看到输出 false ,因为您实际上有!falsefalse是JavaScript中的真值。

window.status already exists (it is used to get/set the text of the browser's status bar) and when a value is assigned to it, it is converted to a string. If you do console.log( status ); you will see that status has the string value "false", which causes you to see the output false, since you effectively have !"false" and "false" is a truthy value in JavaScript.

如果你在函数中做同样的事情,你会得到预期的输出:

If you do the same thing inside a function you'll get the expected output:

(function ( ) {
  var status = false;
  console.log(!status); // true
})();

这篇关于全局范围内的console.log(!status)产生意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆