按位异或(^)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

按位异或^)运算符在两个操作数有且仅有一个对应的二进制位为 1 时,该位的结果值为 1

尝试一下

const a = 5; // 00000000000000000000000000000101
const b = 3; // 00000000000000000000000000000011

console.log(a ^ b); // 00000000000000000000000000000110
// Expected output: 6

语法

js
a ^ b

描述

操作数被转换为 32 位整数并由一系列二进制位(0 和 1)表示。超过 32 位的数字会丢弃其最高有效位。例如,以下超过 32 位的整数将被转换为 32 位整数:

Before: 11100110111110100000000000000110000000000001
After:              10100000000000000110000000000001

第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位第一位第二位第二位,以此类推。

运算符应用于每一对位,结果按位构造。

异或或运算的真值表为:

a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)

将任意数字 x0 进行按位异或运算得到 x

示例

使用按位异或

js
// 9  (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)

14 ^ 9;
// 7  (00000000000000000000000000000111)

规范

Specification
ECMAScript® 2025 Language Specification
# prod-BitwiseXORExpression

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Bitwise XOR (a ^ b)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见