What does x >>> 0 do? [duplicate]

[亡魂溺海] 提交于 2019-12-17 23:46:48

问题


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

I've been trying out some functional programming concepts in a project of mine and I was reading about Array.prototype.map, which is new in ES5 and looks like this:

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

What I'm wondering is why it's doing t.length >>> 0. Because it doesn't seem to do anything. x >>> 0 //-> x! (as long as x is a number, obviously)

Also, note that I don't know how bitwise operators work.


回答1:


x >>> 0 performs a logical (unsigned) right-shift of 0 bits, which is equivalent to a no-op. However, before the right shift, it must convert the x to an unsigned 32-bit integer. Therefore, the overall effect of x >>> 0 is convert x into a 32-bit unsigned integer.

This ensures len is a nonnegative number.

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


来源:https://stackoverflow.com/questions/4081216/what-does-x-0-do

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