>>> 操作符

2017-12-15  本文已影响11人  Scaukk

原生map 函数的实现:

/ 实现 ECMA-262, Edition 5, 15.4.4.19
// 参考: http://es5.github.com/#x15.4.4.19
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");
    }

    // 1. 将O赋值为调用map方法的数组.
    var O = Object(this);

    // 2.将len赋值为数组O的长度.
    var len = O.length >>> 0;

    // 3.如果callback不是函数,则抛出TypeError异常.
    if (Object.prototype.toString.call(callback) != "[object Function]") {
      throw new TypeError(callback + " is not a function");
    }

    // 4. 如果参数thisArg有值,则将T赋值为thisArg;否则T为undefined.
    if (thisArg) {
      T = thisArg;
    }

    // 5. 创建新数组A,长度为原数组O长度len
    A = new Array(len);

    // 6. 将k赋值为0
    k = 0;

    // 7. 当 k < len 时,执行循环.
    while(k < len) {

      var kValue, mappedValue;

      //遍历O,k为原数组索引
      if (k in O) {

        //kValue为索引k对应的值.
        kValue = O[ k ];

        // 执行callback,this指向T,参数有三个.分别是kValue:值,k:索引,O:原数组.
        mappedValue = callback.call(T, kValue, k, O);

        // 返回值添加到新数组A中.
        A[ k ] = mappedValue;
      }
      // k自增1
      k++;
    }

    // 8. 返回新数组A
    return A;
  };      
}

我们要看的是这一句:

var len = O.length >>> 0;

由于对 >>> 操作符不是很了解,就去查了一下,得到如下描述:

This statement copies the length property of the array into a separate variable called len in order to make it faster to access. Using the zero fill right shift bit operator to move the bits in the length zero bits to the right and zero fill is just a fancy shortcut for making the length zero if it is not defined.

大意是说:

借助右移位运算符 ,用零填充 len 左边空出的位。
这样做的好处是: 如果 length 未定义就取 0。

看一下基本用法和示例:

let result = expression1 >>> expression2
>>> 运算符将 expression1 的位右移 expression2 中指定的位数。
用零填充右移后左边空出的位。 右移的位被丢弃。

示例:
'string' >>> 0 ; // 0
null >>> 0 ; // 0
undefined >>> 0; // 0
function a (){};  a >>> 0; // 0
123123 >>> 0; // 123123
-1212 >>> 0; // 4294966084
[] >>> 0; // 0
var a = {}; a >>> 0; // 0
45.2 >>> 0; // 45;

补充一个取整的做法:
~~1.2 // 1
~~ -1.2 // -1

这么写确实比 var len = this.length || 0; 好一些。

而且在遇到意外的 this 时,它不会返回 { }、[ ] 等意外的值(IE 6+ 支持)。

用法总结起来就是:

  1. 所有非数值转换成0 ;
  2. 所有大于等于 0 等数取整数部分;

以上。

上一篇下一篇

猜你喜欢

热点阅读