Home  >  Q&A  >  body text

javascript - ECScript 3 中仿照 ECScript5 中数组的map方法写法,代码中那个if判断有无必要?

//ECScript3中模仿ECScript5中的map方法

Array.prototype.map = Array.prototype.map || function(f){

    var caller = arguments.callee.caller;

    var results = [];
    for(var i = 0; i< caller.length; i++){
    //下面这个if判断还有没有必要?看到书上有这个if判断    
      if(i in caller)  results[i] =   f.call(null,caller[i],i,caller);      
    }

    return results;
};
天蓬老师天蓬老师2748 days ago537

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 12:47:59

    // ES5 环境下
    var arr = [1,,,,,6]; // 这个数组第2至第5项为 undefined
    arr.map(function(item) {
       console.log(item);
    });
    // 1
    // 6
    // 前面是 console.log 的结果,下面是 arr.map() 的返回值
    // [undefined, undefined, undefined, undefined, undefined, undefined]
    

    这个 i in caller 就是用来判断数组里的第i项是否存在 (是否是 undefined)。如果是则不传递给 f 去处理。

    如果没有 i in caller,则在 console 里面会出现 7 行记录。这样和原生的 map 方法的行为就不一致了。

    in 是专门用来判断一个 object 是否包含某个属性的。

    reply
    0
  • Cancelreply