为什么JavaScript中没有逻辑异或?
当前回答
有……类:
if( foo ? !bar : bar ) {
...
}
或者更容易读:
if( ( foo && !bar ) || ( !foo && bar ) ) {
...
}
为什么?不晓得。
因为javascript开发人员认为这是不必要的,因为它可以用其他已经实现的逻辑运算符来表示。
你也可以只用nand,就是这样,你可以从它得到所有其他可能的逻辑运算。
我个人认为它有历史原因,从基于c的语法语言驱动,据我所知,xor不存在或至少非常罕见。
其他回答
试试这个简短易懂的
function xor(x,y){return true==(x!==y);}
function xnor(x,y){return !xor(x,y);}
这适用于任何数据类型
转换为布尔值,然后执行异或,比如-
!!a ^ !!b
有……类:
if( foo ? !bar : bar ) {
...
}
或者更容易读:
if( ( foo && !bar ) || ( !foo && bar ) ) {
...
}
为什么?不晓得。
因为javascript开发人员认为这是不必要的,因为它可以用其他已经实现的逻辑运算符来表示。
你也可以只用nand,就是这样,你可以从它得到所有其他可能的逻辑运算。
我个人认为它有历史原因,从基于c的语法语言驱动,据我所知,xor不存在或至少非常罕见。
是的,按照下面的步骤做。 假设您正在处理布尔值A和B,那么可以使用以下代码在JavaScript中计算XOR B值
var xor1 = !(a === b);
上一行也相当于下面一行
var xor2 = (!a !== !b);
就我个人而言,我更喜欢xor1,因为我需要输入更少的字符。我相信xor1也更快。它只是进行了两次计算。Xor2执行三次计算。
视觉讲解…阅读下面的表格(0代表假,1代表真),比较第3列和第5列。
(a === b):
| A | B | A XOR B | A === B | !(A === B) |
------------------------------------------
| 0 | 0 | 0 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 1 | 0 |
------------------------------------------
享受。
为了子孙后代的利益,也因为我发现这是一个很好的练习,您可以很容易地利用XOR操作符来强制使用真实性。就像被选中的答案一样,它可能有点太聪明了。
const xor = (a, b) => !!(!!a ^ !!b)
console.log(undefined ^ {}) // Returns 0, bitwise can't be done here.
console.log(xor(undefined, {})) // Returns true, because {} is truthy and undefined is falsy
console.log(0 ^ 1) // Works naturally, returns 1
console.log(xor(0, 1)) // Also works, returns true
console.log(true ^ false) // Again, returns true
console.log(xor(true, false)) // And again, returns true...
为了好玩,这应该在TypeScript中工作,通过强制显式的any:
const xor = (a: any, b: any) => !!((!!a as any) ^ (!!b as any))
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标