Exponentiation operator for Boolean in JavaScript?

和自甴很熟 提交于 2019-12-12 02:28:15

问题


Refer to this, the exponentiation operator returns the result of raising first operand to the power second operand, like the exponentiation operator in Python, which is part of the ECMAScript 2016 (ES7) proposal.

We know the result of Boolean with exponentiation operator in Python as following:

>>> False ** False == True
True
>>> False ** True == False
True
>>> True ** False == True
True
>>> True ** True == True
True

I want to know whether the Boolean could be used in the exponentiation operator? If so, could the same behavior as above in Python?


回答1:


I'm not sure what kind of answer you expect. If you look at proposal you will notice that both operands are converted to numbers first. That means false ** false is equivalent to 0 ** 0.

So yes, you can apply the operator to Booleans. Just like with all the other operators, the values are converted to the type that the operator expects.

The result will always be a number.

However, of course if you use loose comparison, then if the result of the exponentiation is 1, it will loosely equal true, if it is 0, it will loosely equal false.




回答2:


Yes

console.log(false ** false == true);  // true
console.log(false ** true == false);  // true
console.log(true ** false == true);  // true
console.log(true ** true == true);  // true

If you use === all of those will be false though because 0 is not the same as false and 1 is not the same as true.



来源:https://stackoverflow.com/questions/33851516/exponentiation-operator-for-boolean-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!