逻辑运算符 ||在 javascript 中,0 代表 Boolean false? [英] Logical operator || in javascript, 0 stands for Boolean false?

查看:15
本文介绍了逻辑运算符 ||在 javascript 中,0 代表 Boolean false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰巧知道下面的代码

代码如下,非常简单:

var test = 0 || -1 ;
console.log(test);

那么控制台中的输出是-1

then the output in the console is -1

不知何故,我对 javascript 真的很陌生,

and somehow i am really new into the javascript,

我想到的是 0 代表 JS 中的布尔 False ,因此 || 运算符似乎忽略了 0 和将值 -1 赋给变量

all i think of is that the 0 stands for Boolean False in JS ,and so || operator seems to ignore the 0 and assign the value -1 to the variable

我说的对吗?我只是想确认一下

so am i right ? i just want a confirm

推荐答案

  • ||expr1 ||expr2 (逻辑或)

    如果可以转换为true则返回expr1;否则,返回 expr2.因此,当与布尔值一起使用时,||如果任一操作数为真,则返回真;如果两者都是假的,则返回假..

    Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false..

  • &&expr1 &&expr2 (逻辑与)

    如果可以转换为false则返回expr1;否则,返回 expr2.因此,当与布尔值一起使用时,&&如果两个操作数都为真,则返回真;否则,返回 false.

    Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

  • Javascript 中的所有值要么是真",要么是假".
    以下值相当于 条件语句中的 false:

    All values in Javascript are either "truthy" or "falsy".
    The following values are equivalent to false in conditional statements:

    • 错误
    • 未定义
    • 空字符串"" ('')
    • 数字 0
    • 数字 NaN

    所有其他值都等价于 true.

    所以... var test = 0 ||-1 ; 返回 -1.

    So... var test = 0 || -1 ; returns -1.

    如果是 var test = 0 ||假 ||未定义 ||"" ||2 ||-1 它将返回 2

    MDN

    这篇关于逻辑运算符 ||在 javascript 中,0 代表 Boolean false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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