按位或 (|)

按位 OR (|) 运算符返回一个数字或 BigInt,其二进制表示形式在每个位位置都有 1,其中任一操作数或两个操作数的对应位为 1

¥The bitwise OR (|) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bits of either or both operands are 1.

Try it

语法

¥Syntax

js
x | y

描述

¥Description

| 运算符针对两种类型的操作数进行重载:编号和 BigInt。对于数字,该运算符返回一个 32 位整数。对于 BigInts,该运算符返回一个 BigInt。它首先 将两个操作数强制转换为数值 并测试它们的类型。如果两个操作数都变为 BigInt,则执行 BigInt OR;否则,它将两个操作数都转换为 32 位整数 并执行数字按位或。如果一个操作数变为 BigInt 而另一个操作数变为数字,则抛出 TypeError

¥The | operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt OR if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number bitwise OR. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

该运算符对 二进制补码 中操作数的位表示进行运算。第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位到第一位,第二位到第二位,依此类推。该运算符应用于每对位,并按位构造结果。

¥The operator operates on the operands' bit representations in two's complement. Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

OR 运算的真值表为:

¥The truth table for the OR operation is:

x y x 或 y
0 0 0
0 1 1
1 0 1
1 1 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)

超过 32 位的数字将丢弃其最高有效位。例如,以下超过 32 位的整数将被转换为 32 位整数:

¥Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before: 11100110111110100000000000000110000000000001
After:              10100000000000000110000000000001

对于 BigInts,没有截断。从概念上讲,将正 BigInt 理解为具有无限数量的前导 0 位,将负 BigInt 理解为具有无限数量的前导 1 位。

¥For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

将任何数字 x0 按位或运算将返回转换为 32 位整数的 x。不要使用 | 0 将数字截断为整数;使用 Math.trunc() 代替。

¥Bitwise ORing any number x with 0 returns x converted to a 32-bit integer. Do not use | 0 to truncate numbers to integers; use Math.trunc() instead.

示例

¥Examples

使用按位或

¥Using bitwise OR

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

14 | 9;
// 15 (00000000000000000000000000001111)

14n | 9n; // 15n

规范

Specification
ECMAScript Language Specification
# prod-BitwiseORExpression

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看