map的整理——面试问题

来源:互联网 发布:ubuntu dhcp server 编辑:程序博客网 时间:2024/06/07 15:31

面试时候遇到遇到一道面试题:[1,2,3,4].map(parseInt);


map是对数组中每个元素执行相同的回调函数,但不修改原数组,而是返回新数组。
现在总结一下有关map的实现原理:

    // 以下是它的实现原理。    if (!Array.prototype.map){   Array.prototype.map = function(fun /*, thisp*/)   {      var len = this.length;      if (typeof fun != "function")      throw new TypeError();      var res = new Array(len);      var thisp = arguments[1];      for (var i = 0; i < len; i++)      {         if (i in this)         res[i] = fun.call(thisp, this[i], i, this);      }      return res;   };}
0 0