peter flanagan
peter flanagan

Reputation: 9790

how to access array when using array.prototype

I am looking at trying to implement the map function myself.

So far my code looks like this:

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];

I am wondering how I can get access to the array I am mapping over in my mapz method?

Upvotes: 1

Views: 144

Answers (4)

Maheer Ali
Maheer Ali

Reputation: 36574

You can use this keyword to access the array

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,5].mapz(double);
console.log(x)

Upvotes: 0

behzad besharati
behzad besharati

Reputation: 6910

You can simply use this

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

Upvotes: 0

jo_va
jo_va

Reputation: 13963

Use the this keywork to access the array inside your function:

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

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could access with 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);

Upvotes: 2

Related Questions