为什么用字符串 + AND (&&) 声明的变量的对数与对 OR (||) 的对数作用不同

Why does the log of a variable declared with string + AND (&&) act differently to doing the same with OR (||)

提问人:Vasso Vassiliades 提问时间:7/15/2022 最后编辑:Vasso Vassiliades 更新时间:7/15/2022 访问量:74

问:

我刚开始学习 JavaScript,在用字符串和 &&(如果先使用字符串时不会显示字符串不会显示)与 Strings 和 ||.

编辑:

我基本上想在控制台 .log 中的布尔值之前输出字符串,现在意识到由于 && 从左到右,这与 ||我需要将数字添加到两边,就像下面代码中“Snippet Edit”注释下方的代码一样(或者我仍然错了?

例:

const passDriversLicense = true;
const hasGoodVision = false;

//OR: Declaring a variable with strings and ||
let shouldDrive = ('1 ' + passDriversLicense || hasGoodVision);

console.log(`${shouldDrive} that she should drive`) // Output in console is "1 true that she should drive"
//AND: Declaring a variable with strings and &&
shouldDrive = ('2 ' + passDriversLicense && hasGoodVision);

console.log(`${shouldDrive} that she should drive`); // Output in console is "false that she should drive" which doesn't have the string before it, like in the OR version IE I would think it should output "2 false that she should drive"

//Snippet Edit
shouldDrive = ('1 ' + passDriversLicense && '1 ' + hasGoodVision);
console.log(`${shouldDrive} that she should drive`);

JavaScript 字符串 变量赋值 运算符 逻辑

评论


答:

0赞 Slava Knyazev 7/15/2022 #1

这称为短路

更一般地说,运算符(&& 和 ||)返回从左到右计算时遇到的第一个假操作数的值,或者如果它们都为真,则返回最后一个操作数的值。

此行为对于以下模式很有用:

const myNumbers = [];
const highestNumber = Math.max(...myNumbers) || 0; // If Math.max() returns a falsy value, it will replace it with a 0 instead

对于特定的 or 值存在类似的工具:运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operatornullundefined??

0赞 CertainPerformance 7/15/2022 #2

去掉不必要的包袱并直接代入值,您的问题归结为:

const one = '1 ' + true || false;
console.log(one);

const two = '2 ' + true && false;
console.log(two);

这应该更清楚地说明发生了什么。

在第一种情况下,左侧是 。这是一个真实的表达,所以整个事情的评估是:。||'1 ' + true'1 true'

在第二种情况下,使用 ,不仅左侧需要计算为真实的表达式,而且右侧也需要计算。但右边是 ,这是不真实的 - 如果左边不真实,则向右边计算。&&false&&

您可以删除 s 以获得相同的效果:+ true

const one = '1 ' || false;
console.log(one);

const two = '2 ' && false;
console.log(two);

评论

0赞 Vasso Vassiliades 7/15/2022
谢谢你!但我认为我需要更清楚,请参阅问题中的编辑
0赞 Tintin 7/15/2022 #3

您需要了解逻辑运算符如何在 Javascript 中使用布尔值。

线路#3passDriversLicense || hasGoodVision = true //because true || false = true

线路#5passDriversLicense && hasGoodVision = false // because true && false = false

请仔细阅读以下内容:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

评论

0赞 Vasso Vassiliades 7/15/2022
我确实明白为什么 #3 和 #5 的答案是真假。这是一个关于日志中字符串的问题,&&的行为与||但现在看到我需要把字符串放在&&IE的两边,let shouldDrive = ('1 ' + passDriversLicense &&'1' + hasGoodVision);