为什么 << 0 会删除 JavaScript 中数字的小数部分?

Why does << 0 remove the decimal portion of a number in JavaScript?

当你有一个浮点数,比如 10.1,并且你在 JavaScript 中使用零填充左移运算符 (<<),它 returns 只是数字的整数部分,例如 10。

这里有一些源代码显示了我的意思:

var num1 = 958.51243

console.log(num1) // 958.51243
console.log(num1 << 0) // 958  

为什么会这样?

查看 docs:

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

因此在执行操作之前,数字将被转换为整数。

对于左移,在官方规范中有描述here:

6.1.6.1.9 Number::leftShift ( x, y )

  1. Let lnum be ! ToInt32(x).

  2. Let rnum be ! ToUint32(y).

  3. (...perform operation...)

ToInt32 的作用:

The abstract operation ToInt32 converts argument to one of 2^32 integer values in the range -2^31 through 2^31 - 1, inclusive.