【问题标题】:Unsigned right shift assignment in JS forEach loop [duplicate]JS forEach循环中的无符号右移赋值[重复]
【发布时间】:2020-07-28 04:57:55
【问题描述】:

我找到了一个 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 &gt;&gt;&gt; 0有什么意义?

【问题讨论】:

    标签: javascript arrays implementation


    【解决方案1】:

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

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

    【讨论】:

    • 这是有道理的。我想了一会儿如果有某种负值并且输出将是一个巨大的数字怎么办,但后来我发现下一条语句if (i in this) 可以防止数组中不存在索引的错误。谢谢!
    猜你喜欢
    • 2012-07-10
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2011-04-02
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多