What is “>>>” operator in JS? [duplicate]

旧时模样 提交于 2020-04-29 10:17:46

问题


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

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 some method:

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;
  };
}

回答1:


>>> 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 length field to an unsigned 31 bit integer, or in other words to "cast" Javascript's native IEEE754 "double" number into an integer.




回答2:


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.



来源:https://stackoverflow.com/questions/10382122/what-is-operator-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!