代码之家  ›  专栏  ›  技术社区  ›  xj9

x>>>0做什么?[副本]

  •  15
  • xj9  · 技术社区  · 14 年前


    What good does zero-fill bit-shifting by 0 do? (a >>> 0)

    我在一个项目中尝试了一些函数式编程的概念 Array.prototype.map ,这是ES5中的新功能,如下所示:

    Array.prototype.map = function(fun) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function") {
            throw new TypeError();
        }
        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in t) {
                res[i] = fun.call(thisp, t[i], i, t);
            }
        }
        return res;
    };
    

    我想知道的是为什么 t.length >>> 0 . 因为它似乎什么也做不了。 x >>> 0 //-> x ! (显然,只要x是一个数字)

    另外,请注意,我不知道按位运算符是如何工作的。

    1 回复  |  直到 7 年前
        1
  •  23
  •   kennytm    14 年前

    x >>> 0 执行0位的逻辑(无符号)右移,相当于no-op。但是,在右移之前,它必须转换 x x>>>0 正在转换 变成32位无符号整数。

    这确保了 len

    js> 9 >>> 0
    9
    js> "9" >>> 0
    9
    js> "95hi" >>> 0
    0
    js> 3.6 >>> 0
    3
    js> true >>> 0
    1
    js> (-4) >>> 0
    4294967292