什么是x>>> 0呢?

时间:2010-11-02 19:04:29

标签: javascript bitwise-operators

  

可能重复:
  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 个答案:

答案 0 :(得分:22)

x >>> 0执行0位的逻辑(无符号)右移,相当于无操作。但是,在右移之前,它必须将x转换为无符号的32位整数。因此,x >>> 0的整体效果是将x转换为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