Adding a second solution with a "for" loop (#35299)

* Adding a second solution with a "for" loop

+ adapted some texts to make the whole thing coherent
+ added some Useful links at the end of the article

* Update index.md

* Update index.md

* Update index.md

* Update index.md

* Update index.md

* Update index.md
This commit is contained in:
Catherine
2019-03-28 13:31:46 +01:00
committed by The Coding Aviator
parent 26bb9b6585
commit 1df0fcdb9f

View File

@ -4,11 +4,11 @@ title: Implement map on a Prototype
## Implement map on a Prototype
To solve THIS challenge using the keyword this is a key.
### Solution 1 - Solve this challenge using `this` and the forEach method
It will give us access to the object we are calling myMap.
The `this` keyword gives us access to the object we are calling myMap on.
From there we can use the forEach or for loop to add elements to already declared empty array as we modify each element with the given callback method.
From there we can use the forEach method to add elements to already declared empty array as we modify each element with the given callback method.
```javascript
// the global Array
@ -28,6 +28,34 @@ var new_s = s.myMap(function(item){
});
```
### Solution 2 - Solve this challenge using a "for" loop and `this`
The use of a "for" loop allows us to apply the callback function to every item in the Global array and then push the modified items to the empty new array that is returned in the end.
```javascript
// The global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
```
### Useful Links
[this. JavaScript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)<br/>
[this. JavaScript W3Schools](https://www.w3schools.com/js/js_this.asp)
[this. Javascript W3Schools](https://www.w3schools.com/js/js_this.asp)
[for loop MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)
[Array.prototype MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype)