javascript - 使用 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)));)
解决方案
推荐阅读
- java - Jenkins 超时,因为 bitbucket repo .git 文件夹包含大量数据
- salesforce-marketing-cloud - 在营销云中完成任务后创建内部微调
- javascript - 在 React java 脚本中传递参数
- javascript - 如何将 ("1,2,3") 转换为 ("1","2","3")
- javascript - 拆分文本并将其包装在 span 元素中
- python - Python:如何将年中的一天转换为日和月?
- javascript - 已删除库中的 console.logs 仍显示在客户端上
- powershell - Powershell - 根据另一个 zip 文件的内容压缩文件
- c# - 如何读取一行并声明以读取值命名的变量 c#
- sql - 每 4 条记录/行的 SQL 批号