简体   繁体   English

访问回调array.protoype中的参数

[英]accessing arguments in callback array.protoype

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. 要访问我要映射的数组,我将根据之前的问题使用this Now I am wondering how to access different arguments passed to the callback . 现在,我想知道如何访问传递给callback不同参数。 So in the official map method you can pass the index. 因此,在官方map方法中,您可以传递索引。 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); 

You just need to add another argument to your callback function which is your index. 您只需要在回调函数中添加另一个参数即索引即可。

 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); return item * 2; }) console.log(x); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM