javascript 什么是 JS 中的“>>>”运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10382122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:40:51  来源:igfitidea点击:

What is ">>>" operator in JS?

javascriptarraysiteratoroperators

提问by Green

Possible Duplicate:
javascript >>> operator?
JavaScript triple greater than

可能重复:
javascript >>> 运算符?
JavaScript 三重大于

Found this operator in such line of code:

在这样的代码行中找到了这个运算符:

var t = Object(this),
        len = t.length >>> 0;

What does this operator mean?

这个运算符是什么意思?

Full code is below. It is the code of JS somemethod:

完整代码如下。这是JSsome方法的代码:

if (!Array.prototype.some) {
  Array.prototype.some = function(fun /*, thisp */) {
    "use strict";

    if (this == null) throw new TypeError();

    var t = Object(this),
        len = t.length >>> 0;

    if (typeof fun != "function") throw new TypeError();

    var thisp = arguments[1];

    for (var i = 0; i < len; i++) {
      if (i in t && fun.call(thisp, t[i], i, t))
        return true;
    }

    return false;
  };
}

回答by Alnitak

>>>is a right shift without sign extension

>>>没有符号扩展的右移

If you use the >>operator on a negative number, the result will also be negative because the original sign bit is copied into all of the new bits. With >>>a zero will be copied in instead.

如果>>在负数上使用运算符,结果也将为负数,因为原始符号位被复制到所有新位中。随着>>>零将不是被复制。

In this particular case it's just being used as a way to restrict the lengthfield to an unsigned 31 bit integer, or in other words to "cast" Javascript's native IEEE754 "double" number into an integer.

在这种特殊情况下,它只是用作将length字段限制为无符号 31 位整数的一种方式,或者换句话说,将 Javascript 的本机 IEEE754“双”数“转换”为整数。

回答by tskuzzy

It's a zero-fill right shift. When you bit-shift a number, you can either decide to fill the left-most bits with zeros or with the sign bit.

这是一个零填充右移。当您对数字进行位移时,您可以决定用零或符号位填充最左边的位。

In a two's complement number representation, negative numbers have a 1 as the leading bit whereas positive numbers have a 0. Thus if you don't "sign extend" (filling with zeros instead) and shift a negative number, it will result in a positive number.

在二进制补码表示中,负数的前导位为 1,而正数的前导位为 0。因此,如果您不“符号扩展”(用零填充)并移动负数,它将导致正数。