Reputation: 9790
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
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
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
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
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