2010-11-02 97 views
15

可能重复:
What good does zero-fill bit-shifting by 0 do? (a >>> 0)x >>> 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是一个数字,显然)

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

+0

和许多其他的http://stackoverflow.com/questions/1822350/ http://stackoverflow.com/questions/1474815/ http://stackoverflow.com/questions/1385491/的http:// stackoverflow.com/questions/3348438/只有当找到第一个> _>时才能很容易地找到它们。 – kennytm 2010-11-02 19:16:50

+1

@KennyTM〜好的重复,如果你知道事物的名字是...;) – jcolebrand 2010-11-02 19:31:09

回答

21

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 
+0

你能解释为什么something.length会小于0吗? – Patriks 2015-01-28 11:05:41

+0

@Pratik为什么它会是'真'?它可能没有现实世界的理由。但是如果它发生(例如偶然),它会破坏'.map'。示例代码:'Array.prototype.map.call({length:-2},f)' – m93a 2015-04-26 09:21:15