首页 > 解决方案 > JS forEach循环中的无符号右移赋值

问题描述

我找到了一个 javascript forEach 循环的实现,但有一件事让我很困扰。

if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function") {
        throw new TypeError();
    }

    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in this) {
            fun.call(thisp, this[i], i, this);
        }
    }
};
}

无符号右移有什么意义this.length >>> 0

标签: javascriptarraysimplementation

解决方案


这是一种确保它len是 32 位无符号整数的方法。

通过使用>>> 0,您永远无法获得NaN或负值。


推荐阅读