首页 > 解决方案 > 使用 for 循环等效实现 Array.prototype.map

问题描述

我正在尝试使用“for循环”实现一个等效于 Array.prototype.map 的地图版本,它的工作原理相似,但最终,它给了我一些不寻常的东西。

我的代码如下:

// the global Array

1. var s = [23, 65, 98, 5];

2. Array.prototype.myMap = function(callback){
3.   var newArray = [];

4.  console.log(this); // prints 23,65,98,5 which is correct
5.  for(let element in this){
6.    console.log(this[element]); // this line and the push doesn't work well
7.    newArray.push(callback(this[element]));
8.    console.log("element: " + newArray);
9.  }
10.    console.log("final: " + newArray);
11.  return newArray;
12. };

13. var new_s = s.myMap(function(item){
14.     return item * 2;
15. });

`

代码的输出如下:

23,65,98,5
23
elem: 46
65
elem: 46,130
98
elem: 46,130,196
5
elem: 46,130,196,10
function (callback) {
  var newArray = [];

  window.__console.log(this);
  for (var element in this) {
    window.__console.log(this[element]);
    newArray.push(callback(this[element]));
    window.__console.log("elem: " + newArray);
  }
  window.__console.log("final: " + newArray);
  return newArray;
}
elem: 46,130,196,10,NaN
final: 46,130,196,10,NaN

如果你看,最终的数组正在打印 NaN,因为添加了函数(回调),但奇怪的是,在声明一个 newArray 的行之后,我正在记录“this”(第 4 行),函数(回调)不添加。有人可以解释发生了什么以及为什么要添加它吗?如果不是 for 循环,我添加了 forEach 循环它可以正常工作,只有 for 循环是它的行为怪异。(this.forEach(a => newArray.push(callback(a)));)

标签: javascriptarray.prototype.map

解决方案


推荐阅读