函数式编程:在原型上实现映射 [英] Functional programming: implement map on a prototype

查看:77
本文介绍了函数式编程:在原型上实现映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写自己的Array.prototype.myMap(),它的行为应该与Array.prototype.map()完全相同。你可以使用for循环方法。



#new_s应该等于[46,130,196,10]。

#代码应该不使用地图方法。





我的代码:

i have to write my own Array.prototype.myMap(), which should behave exactly like Array.prototype.map(). You may use a for loop method.

#new_s should equal [46, 130, 196, 10].
#The code should not use the map method.


my code:

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  for(let i = 0; i < s.length; i++){
    newArray.push(this[i]);
  }

  // Add your code above this line
  return newArray;

};

var new_s = s.myMap( (item) => {return item * 2;} ); // outputs: [23,65,98,5] -- why?





我的尝试:



一次又一次读取和重写代码。



What I have tried:

read and rewrite again and again the code.

推荐答案

引用:

输出:[23,65,98,5] - 为什么?

outputs: [23,65,98,5] -- why?



您的代码行为不正常你期望,或者你不明白为什么!



有一个几乎通用的解决方案:一步一步地在调试器上运行你的代码,检查变量。

调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

调试器中没有魔法,它不知道是什么你的代码应该做,它没有发现错误,它只是通过向你展示发生了什么来帮助你。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行,并在执行时检查变量。



调试器 - 维基百科,免费的百科全书 [ ^ ]


掌握调试Visual Studio 2010 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]



JavaScript调试 [< a href =https://www.w3schools.com/js/js_debugging.asptarget =_ blanktitle =New Window> ^ ]

Chrome DevTools  | 网络  |  Google Developers [ ^ ]



这里的调试器只显示你的代码正在做什么,你的任务是与它应该做什么进行比较。


Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

JavaScript Debugging[^]
Chrome DevTools  |  Web  |  Google Developers[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


这篇关于函数式编程:在原型上实现映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆