开发者

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

开发者 https://www.devze.com 2023-01-23 08:54 出处:网络
This question already exists: Closed 12 years ago. Possible Duplicate: What good does zero-fill bit-shifting by 0 do? (a >>> 0)
This question already exists: Closed 12 years ago.

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消