JavaScript 扩展 Array 以实现 map2

JavaScript extending Array to implement map2

本文关键字:实现 map2 Array 扩展 JavaScript      更新时间:2023-09-26

我想扩展javascript Array来实现map2功能,而无需使用内置的map函数。其中 map2 功能将数组的传递值加倍。

例如:

var m = [1,2,3,4,5]
var double = [1,2,3,4,5].map2(doubleFn)
console.log(double) should output 2,4,6,8,10

并且上述功能需要在不使用任何内置的JS数组方法的情况下进行开发

代码片段

 Array.prototype.map2= function(callback, thisArg){
      var len=this.length
      for(var i in this){
        callback.call(this,this[i]*2)
      } 
   }

请让我知道,我可以遵循什么方法来执行此操作

Array.prototype.map2 = function (callback, thisArg){
  var i, el,
      len   = this.length,
      res   = [],
      _this = thisArg ? thisArg : this;
  for (i = 0; i < len; i++) {
    el     = this[i];  // also you can use this[i] * 2 - it depend what do want; 
    res[i] = callback.call(_this, el);    
  }
  return res;
};
var double = [1,2,3,4,5].map2(function (el) {
  return el * 2;
});

关于你的错误,不要对数组使用for..inmap你需要创建新数组并返回它......

我猜你想重新实现内置的Array.prototype.map.这是执行此操作的方法之一:

Array.prototype.map2 = function(f1){
  var a = [];
  this.forEach(function(element){
    a.push(f1(element));
  })
  return a;
}
a = [1,2,3,4,5]
console.log(a.map2(function(a){return a<<1;});
//output: [ 2, 4, 6, 8, 10 ]

编辑:不使用内置函数:

Array.prototype.map2 = function(f1){
  var a = [];
  var that = this;
  return (function recArray(index, target){
    if(typeof(that[index]) !== 'undefined') {
      target[index] = f1(that[index]);
      return recArray(index + 1, target);
    }
    return target;
  })(0, a);
}

但是这个解决方案有一个问题:

如果输入数组有孔怎么办:

a = [1,2,3,4,5]
a[12] = 11
//now a is: [ 1, 2, 3, 4, 5, , , , , , , , 11 ]

JavaScript 数组可以有漏洞,如果两者之间有undefined值,那么上述方法将失败。如果不知道数组的长度,如果它包含"孔",则无法遍历它。

显式存储长度没有意义,因为它存储在Array.prototype.length中。因此,如果数组不连续,那么不使用长度就不可能实现map