javascript - In map implementation in js, var len = O.length >>> 0;
ringa_lee
ringa_lee 2017-05-18 10:57:55
0
3
893
if (!Array.prototype.map) {
  Array.prototype.map = function(callback, thisArg) {
    var T, A, k;
    if (this == null) {
      throw new TypeError(" this is null or not defined");
    }
    var O = Object(this);
    var len = O.length >>> 0;
    // 3.如果callback不是函数,则抛出TypeError异常.
    if (Object.prototype.toString.call(callback) != "[object Function]") {
      throw new TypeError(callback + " is not a function");
    }
    if (thisArg) {
      T = thisArg;
    }
    A = new Array(len);
    k = 0;
    while(k < len) {
      var kValue, mappedValue;
      if (k in O) {
        kValue = O[ k ];
        mappedValue = callback.call(T, kValue, k, O);
        A[ k ] = mappedValue;
      }
      k++;
    }
    return A;
  };      
}

var len = O.length >>> 0; What is the purpose of the bit operators here

ringa_lee
ringa_lee

ringa_lee

reply all(3)
过去多啦不再A梦

Personal understanding:

Because although this map method is on the prototype of Array, when it is actually called, this is not necessarily of Array type, and the length cannot be guaranteed. After adding bit operations, the uncertain value can be converted into Number.

1 >>> 0 // 1
undefined >>> 0 // 0
null >>> 0 // 0
'string' >>> 0 // 0
Peter_Zhu

Convert any JS value into a number without NaN

Peter_Zhu
  1. All non-numeric values ​​are converted to 0

  2. All numbers greater than or equal to 0 take the integer part

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template