左移 (<<)
左移 (<<
) 运算符返回一个数字或 BigInt,其二进制表示形式是向左移动指定位数的第一个操作数。向左移出的多余位将被丢弃,并且从右侧移入零位。
¥The left shift (<<
) operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.
Try it
语法
描述
¥Description
<<
运算符针对两种类型的操作数进行重载:编号和 BigInt。对于数字,该运算符返回一个 32 位整数。对于 BigInts,该运算符返回一个 BigInt。它首先 将两个操作数强制转换为数值 并测试它们的类型。如果两个操作数都变成 BigInt,则执行 BigInt 左移;否则,它将两个操作数都转换为 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 left shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number left shift. A TypeError
is thrown if one operand becomes a BigInt but the other becomes a number.
该运算符对 二进制补码 中左操作数的位表示进行运算。例如,9 << 2
产生 36:
¥The operator operates on the left operand's bit representation in two's complement. For example, 9 << 2
yields 36:
9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
将 32 位整数 x
按位向左 y
位生成 x * 2 ** y
。例如,9 << 3
相当于 9 * (2 ** 3) = 9 * (8) = 72
。
¥Bitwise a 32-bit integer x
to the left by y
bits yields x * 2 ** y
. So for example, 9 << 3
is equivalent to 9 * (2 ** 3) = 9 * (8) = 72
.
如果左操作数是超过 32 位的数字,则会丢弃最高有效位。例如,以下超过 32 位的整数将被转换为 32 位整数:
¥If the left operand is a number with more than 32 bits, it will get the 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
右操作数将转换为无符号 32 位整数,然后对 32 取模,因此实际移位偏移量始终是 0 到 31 之间的正整数(含 0 和 31)。例如,100 << 32
与 100 << 0
相同(并生成 100
),因为 32 模 32 为 0。
¥The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 << 32
is the same as 100 << 0
(and produces 100
) because 32 modulo 32 is 0.
对于 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.
将任何数字 x
左移 0
返回转换为 32 位整数的 x
。不要使用 << 0
将数字截断为整数;使用 Math.trunc()
代替。
¥Left shifting any number x
by 0
returns x
converted to a 32-bit integer. Do not use << 0
to truncate numbers to integers; use Math.trunc()
instead.
示例
使用左移
规范
Specification |
---|
ECMAScript Language Specification # sec-left-shift-operator |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also