Javascript逻辑运算符和结果 [英] Javascript logical operators and results

查看:120
本文介绍了Javascript逻辑运算符和结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道大多数语言中逻辑运算的结果是true,false或1,0. 在Javascript中,我尝试了以下操作:

I know that the result of logical operations in most of the languages is either true, false or 1,0. In Javascript I tried the following:

alert(6||5)  // => returns 6
alert(5||6)  // => returns 5
alert(0||5)  // => returns 5
alert(5||0)  // => returns 5
alert(5||1)  // => returns 5
alert(1||5)  // => returns 1
alert(5&&6)  // => returns 6
alert(6&&5)  // => returns 5
alert(0&&5)  // => returns 0
alert(5&&0)  // => returns 0
alert(-1&&5) // => returns 5
alert(5&&-1) // => returns -1  

那么逻辑运算符的结果是什么?如果一个操作数为0或1,则它将按预期工作.如果两者均为非零且非1,则

So what is the result of logical operators? If one operand is 0 or 1 then it works as expected. If both are nonzero and other than 1 then

  1. 如果为逻辑or,则返回第一个操作数
  2. 如果为逻辑and,则返回第二个操作数
  1. In case of logical or, the first operand is returned
  2. In case of logical and, the second operand is returned

这是一般规则吗?

我不知道的另一件事是运算符|.

Another thing I dont know is the operator |.

我尝试了运算符|并获得了不同的结果:

I have tried the operator | and gotten different results:

alert(5|8)  // => returns 13 
alert(8|5)  // => returns 13 
alert(-5|8) // => returs -5
alert(8|-5) // => returns -5
alert(0|1)  // => returns 1 
alert(1|0)  // => returns 1
alert(1|1)  // => returns 1

该操作员实际做什么?

推荐答案

由于javascript不是一种类型化的语言,因此可以在逻辑运算符上使用任何对象,如果该对象为null,false布尔值,空字符串,0或一个未定义的变量,则其作用类似于false,如果它有其他含义,则其作用类似于true

Since javascript is not a typed languaged any object can be used on logical operators, if this object is null, a false boolean, an empty string, a 0 or an undefined variable then it acts like a false if it's anything else then it is like a true

逻辑运算结束时,最后一个检查值返回.

At the end of the logical operation the last checked value returns.

所以

6 || 2

Check first value -> "6"
6 = true
Go to next value -> "2"
2 = true

操作结束,返回最后一个值. 2,如果传递给另一个逻辑操作,它将与true相同.

这是一个错误的陈述. 6||2返回6,因为6充当true足以知道条件OR为真,而无需检查下一个值.

that was a wrong statement. 6||2 returns 6 because 6 acting as true is enough to know the condition OR is true without the need to check the next value.

这实际上与

true || true

true||true

Check first value -> "true"
Check next value -> "true"
return last value -> "true"

并且为6&& 0&& 2

And for 6 && 0 && 2

First value 6 = true
Next value 0 = false

在此处停止操作,并返回上次检查的值:0.

Stop operation here and returns the last checked value: 0.

运算符是另一回事,它只是在输入值的位上执行逻辑或,如akp在另一个答案中所述.

The | operator is a whole different thing, it simply peforms a logical OR on the bits of the input values, as explaned on the other answer by akp.

这篇关于Javascript逻辑运算符和结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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