gpt4 book ai didi

javascript - 使用 array.prototype 时如何访问数组

转载 作者:行者123 更新时间:2023-11-30 11:09:06 25 4
gpt4 key购买 nike

我正在尝试自己实现 map 函数。

到目前为止,我的代码如下所示:

Array.prototype.mapz = function (callback) {
let arr = []
for (let i = 0; i < array.length; i++) {
arr.push(callback(array[i]));
}
return arr;
};

function double(arg) {
return arg * 2
};

const x = [1, 2, 3].mapz(double);
console.log(x); // This should be [2, 3, 6];

我想知道如何访问我在 mapz 方法中映射的数组?

最佳答案

您可以使用 this 访问.

Array.prototype.mapz = function (callback) {
let arr = [];
for (let i = 0; i < this.length; i++) {
arr.push(callback(this[i]));
}
return arr;
};

function double(arg) {
return arg * 2;
}

const x = [1, 2, 3].mapz(double);
console.log(x);

关于javascript - 使用 array.prototype 时如何访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com