JavaScript 扩展 Array 以实现 map2
JavaScript extending Array to implement map2
我想扩展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..in
,map
你需要创建新数组并返回它......
我猜你想重新实现内置的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
。
相关文章:
- 如何使用动画实现纸张推车
- 客户端服务器REST API captcha实现
- 如何实现此布局
- Meteor忘记了密码的实现
- 使用Native Sockets在Android中实现WebSockets
- 在样板文件中实现Ajax
- instanceof是如何在JavaScript中实现的
- 如何正确实现Jquery多选小部件
- 实现一个建立在google.com之上的自定义搜索引擎
- 多个组件是如何实现的
- window.location使用jquery mobile实现chrome跳转
- 如何在OpenERP中实现网络摄像头
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- javascript加密实现,包括可信否认
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 如何让程序员在javascript中实现正确的回调
- 如何使用自定义辅助对象(handler)实现嵌套的每个循环
- AngularJS智能表全局配置实现
- Expressjs/AngularJS:实现req-flash后出错
- JavaScript 扩展 Array 以实现 map2