运算符>>>(零填充右移)在 Array.prototype.find (polyfill) 中的用法



我正在查看这个函数Array.prototype.find从(mdn polyfill):

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;
    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

我不明白这段代码的目的:

var length = list.length >>> 0;

x >>> 0强制x变为整数。因此,如果list是一个数组,则length为其长度;但是如果.length不存在,或者是像{a: 17, length: "Unicorns"}这样愚蠢的东西,length将是0

在任何javascript二进制操作中都存在隐式的"转换为int"。因此,3.14159 >>> 0 === 3和任何无效值,如'foo',都被强制转换为0

为什么是>>>而不是>>| ?显然,他们期望巨大的数组(但不是太大):

Math.pow(2,31)>>0
-2147483648
Math.pow(2,31)>>>0
2147483648

最新更新