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

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

问题描述

我碰巧知道以下code

这里是code,也很简单:

  VAR测试= 0 || -1;
的console.log(试验);

再在控制台输出 1

不知何故我真的进入新的JavaScript,

所有我想到的是,在 0 表示布尔在JS,所以 || 运营商似乎忽略0和值-1分配给变量

这样对吗?
我只是想要一个确认


解决方案

  • ||表达式1 ||表达式2 (逻辑OR)


      

    将返回EXPR1如果它可以被转化为true;否则,返回表达式2。因此,布尔值使用时,||返回true,如果操作数是真实的;如果两个都是假的,返回false。



  • &放大器;&安培;表达式1&放大器;&安培;表达式2 (逻辑与)


      

    将返回EXPR1如果它可以转换为假;否则,返回表达式2。因此,布尔值,和功放使用时;&放大器;如果两个操作数都是真的返回true;否则,返回false。



在Javascript中所有的值为truthy或falsy。结果
以下值等同于虚假的条件语句




  • 未定义

  • 空字符串(\\

  • 数字0

  • 的数量为NaN

所有其他值都等同于真实的。


所以... VAR测试= 0 || -1; 收益 1

如果是 VAR测试= 0 ||假||未定义|| || 2 || -1 它会返回 2


在<逻辑运算符href=\"https://developer.mozilla.org/en/JavaScript/Guide/Ex$p$pssions_and_Operators#Logical_operators\">MDN

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

and somehow i am really new into the javascript,

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 (Logical OR)

    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 (Logical AND)

    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.

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

  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN

All other values are equivalent to true.


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

If it was var test = 0 || false || undefined || "" || 2 || -1 it would return 2


Logical operator on MDN

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

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