简体   繁体   English

Javascript真条件未检测到布尔值

[英]Javascript true condition not detecting boolean

I have this part of code:我有这部分代码:

   let values = true;

let msg = 'message1';
        if(values) {let msg = 'message2';}

        console.log(msg);

And I always have message1 in console log.而且我总是在控制台日志中有message1

As I know, the if(values) should satisfy the if statement for any truthy value of values including true, any non-zero number, any non-empty string value, any object or array reference, etc...据我所知, if(values)应该满足任何真值的 if 语句,包括真值、任何非零数字、任何非空字符串值、任何对象或数组引用等......

So why is it not working?那么为什么它不起作用呢?

There are no issues with if statement. if语句没有问题。 It's correctly running but the problem is that you have defined msg variable again with let msg = 'message2';它正确运行,但问题是您再次使用let msg = 'message2';定义了msg变量let msg = 'message2';

That should be replaced with msg = 'message2' and it will work.应该用msg = 'message2'替换它,它会起作用。

 let values = true; let msg = 'message1'; if(values) { msg = 'message2'; } console.log(msg);

The scope of a variable declared using let is the most inner block of code that contains it. 使用let声明变量的范围是包含它的最内部的代码块。

In your example there are two different variables named msg .在您的示例中,有两个名为msg不同变量。

The first one ( let msg = 'message1') is the one printed by console.log(msg);`.第一个 ( let msg = 'message1') is the one printed by console.log(msg);` let msg = 'message1') is the one printed by

The second one (let msg = 'message2') exists only in the block ( {...} ) where it is declared.第二个 (let msg = 'message2') 仅存在于声明它的块 ( {...} ) 中。 It is destroyed when the code execution leaves the block (at } ).当代码执行离开块(在} )时,它会被销毁。
Inside that block the outer variable named msg is not available.在该块内,名为msg的外部变量不可用。

There is no need to declare a variable multiple times (unless your purpose is to get the effect you encountered now).不需要多次声明一个变量(除非你的目的是为了得到你现在遇到的效果)。 Declare it only once, before it is used for the first time.在第一次使用之前,只声明一次。

This code works as expected:此代码按预期工作:

let values = true;
let msg = 'message1';

if (values) {
  msg = 'message2';
}

console.log(msg);

You can add a console.log() calls inside the if block to check that it is executed (because the condition is true ):您可以在if块中添加console.log()调用以检查它是否已执行(因为条件为true ):

 let values = true; let msg = 'message1'; if (values) { let msg = 'message2'; console.log('inner: ' + msg); } console.log('outer: ' + msg);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM