javascript - js中map实现中 var len = O.length >>> 0;

查看:283
本文介绍了javascript - js中map实现中 var len = O.length >>> 0;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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; 这里位运算符目的是什么

解决方案

個人理解:

因爲雖然這個 map 方法是在Array 的 prototype上的,但實際上調用的時候,this 不一定是 Array類型,length不能得到保證,加上位運算後,可以將不確定的値轉換成Number。

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

这篇关于javascript - js中map实现中 var len = O.length &gt;&gt;&gt; 0;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆