有很多文章都有在看js 的 === 与 == 的区别,突然 看 读lodash源码之从slice看稀疏数组与密集数组 时,看到 >>> ,就有想知道 >>> 与 >> 有什么区别呢?


从ECMAScript 2019中 >> 与 >>> 的描述大体相同,


12.9.4.1Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression>>AdditiveExpression

  1. Let lref be the result of evaluating ShiftExpression.
  2. Let lval be ? GetValue(lref).
  3. Let rref be the result of evaluating AdditiveExpression.
  4. Let rval be ? GetValue(rref).
  5. Let lnum be ? ToInt32(lval).
  6. Let rnum be ? ToUint32(rval).
  7. Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
  8. Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The result is a signed 32-bit integer.

12.9.5.1Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression>>>AdditiveExpression

  1. Let lref be the result of evaluating ShiftExpression.
  2. Let lval be ? GetValue(lref).
  3. Let rref be the result of evaluating AdditiveExpression.
  4. Let rval be ? GetValue(rref).
  5. Let lnum be ? ToUint32(lval).
  6. Let rnum be ? ToUint32(rval).
  7. Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
  8. Return the result of performing a zero-filling right shift of lnum by shiftCount bits. Vacated bits are filled with zero. The result is an unsigned 32-bit integer.



具体讲就是最后一句有区别,谷歌翻译分别为


  1. 为 返回通过shiftCount位执行lnum的符号扩展右移的结果。传播最重要的位。结果是带符号的32位整数。

  2. 为 返回通过shiftCount位执行lnum的零填充右移的结果。空位用零填充。结果是无符号的32位整数。


到这里就比较明确了,>> 与 >>> 返回结果均为32位数字,但是 >> 是带符号扩展 , 而 >>> 是无符号位移

搜了下无符号右移,发现好像是惯例,~~ emmm打扰了,不过也是自己第一次不靠度娘,通过规范知道的呢,还是记录一下。