访问回调array.protoype中的参数 [英] accessing arguments in callback array.protoype
本文介绍了访问回调array.protoype中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在实现地图功能.要访问我要映射的数组,我根据前面的问题使用了this
.现在,我想知道如何访问传递给callback
的不同参数.因此,在官方的map
方法中,您可以传递索引.我正在尝试执行此操作,但是不确定如何在我的自定义方法中访问它.
I am implementing the map function. To access the array I am mapping over I am using this
based on a question I had earlier. Now I am wondering how to access different arguments passed to the callback
. So in the official map
method you can pass the index. I am trying to do this, but unsure how to access this in my custom method.
Array.prototype.mapz = function(callback) {
const arr = [];
for (let i = 0; i < this.length; i++) {
arr.push(callback(this[i]))
}
return arr;
};
let x = [1, 12, 3].mapz((item, index) => {
return item * 2;
})
console.log(x);
推荐答案
您需要将索引作为回调的第二个参数
You need to hand over the index as second parameter for the callback
Array.prototype.mapz = function(callback) {
const arr = [];
for (let i = 0; i < this.length; i++) {
arr.push(callback(this[i], i));
}
return arr;
};
let x = [1, 12, 3].mapz((item, index) => {
console.log(index, item);
return item * 2;
})
console.log(x);
这篇关于访问回调array.protoype中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文