[英]Logical operator || in javascript, 0 stands for Boolean false?
I happened to know the following code我碰巧知道以下代码
Here is the code, and very simple:这是代码,非常简单:
var test = 0 || -1 ;
console.log(test);
then the output in the console is -1那么控制台中的输出是-1
and somehow i am really new into the javascript,不知何故,我对javascript真的很陌生,
all i think of is that the 0 stands for Boolean False in JS ,and so ||
我想到的是0代表 JS 中的 Boolean False ,所以
||
operator seems to ignore the 0 and assign the value -1 to the variable运算符似乎忽略了 0 并将值 -1 分配给变量
so am i right ?那我说得对吗? i just want a confirm
我只想确认
||
— expr1 || expr2
—
expr1 || expr2
expr1 || expr2
(Logical OR) expr1 || expr2
(逻辑或)
Returns expr1 if it can be converted to true;
如果可以转换为 true,则返回 expr1; otherwise, returns expr2.
否则,返回 expr2。 Thus, when used with Boolean values, ||
因此,当与布尔值一起使用时, || returns true if either operand is true;
如果任一操作数为真,则返回真; if both are false, returns false..
如果两者都为假,则返回假..
&&
— expr1 && expr2
(Logical AND) &&
— expr1 && expr2
(逻辑与)
Returns expr1 if it can be converted to false;
如果可以转换为 false,则返回 expr1; otherwise, returns expr2.
否则,返回 expr2。 Thus, when used with Boolean values, && returns true if both operands are true;
因此,当与布尔值一起使用时,如果两个操作数都为真,&& 返回真; otherwise, returns false.
否则,返回 false。
All values in Javascript are either "truthy" or "falsy". Javascript 中的所有值要么是“真”,要么是“假”。
The following values are equivalent to false in conditional statements :以下值在条件语句中等效于 false:
""
(\\ ''
)""
(\\ ''
) All other values are equivalent to true.所有其他值都等价于 true。
So... var test = 0 || -1 ;
所以...
var test = 0 || -1 ;
var test = 0 || -1 ;
returns -1
.返回
-1
。
If it was var test = 0 || false || undefined || "" || 2 || -1
如果是
var test = 0 || false || undefined || "" || 2 || -1
var test = 0 || false || undefined || "" || 2 || -1
var test = 0 || false || undefined || "" || 2 || -1
it would return 2
var test = 0 || false || undefined || "" || 2 || -1
它将返回2
You can use Nullish coalescing operator (??)您可以使用Nullish 合并运算符 (??)
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
Only null and undefined will be falsey.只有 null 和 undefined 是假的。 0 will be considered true.
0 将被视为真。 But take care: an empty string will be considered true too!
但请注意:空字符串也会被认为是真的!
console.log('0 ?? 1 ->', 0 ?? 1) // expected output: 0 console.log('null ?? 1 -> ', null ?? 1) // expected output: 1 console.log('undefined ?? 1 ->', undefined ?? 1) // expected output: 1 console.log('"" ?? 1 ->', "" ?? 1) // expected output: ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.