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

标签 javascript ecmascript-6

我正在尝试自己实现 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/

相关文章:

用于绑定(bind)对象中指定事件的 JavaScript 函数

Javascript RegExp 多重规则

javascript - 隐藏链接的默认悬停 CSS

javascript - 将 Intl.DateTimeFormat 理解为 JavaScript 对象

javascript - 箭头函数的性能和内存占用

javascript - array.push 不是函数 - 使用 reduce 时

javascript - 使用数组和对象形成对象数组

javascript - 如何将毫秒转换为日期字符串?

javascript - 如何在javascript中过滤多维数组中的对象?

javascript - ES6 生成器 : input value for . next()