I am trying to implement a version of map that is equivalent to Array.prototype.map using "for loop" and it works similarly yet in the end, it gives me something unusual.
My code is as below:
// the global Array
1. var s = [23, 65, 98, 5];
2. Array.prototype.myMap = function(callback){
3. var newArray = [];
4. console.log(this); // prints 23,65,98,5 which is correct
5. for(let element in this){
6. console.log(this[element]); // this line and the push doesn't work well
7. newArray.push(callback(this[element]));
8. console.log("element: " + newArray);
9. }
10. console.log("final: " + newArray);
11. return newArray;
12. };
13. var new_s = s.myMap(function(item){
14. return item * 2;
15. });
`
The output of the code is as below:
23,65,98,5
23
elem: 46
65
elem: 46,130
98
elem: 46,130,196
5
elem: 46,130,196,10
function (callback) {
var newArray = [];
window.__console.log(this);
for (var element in this) {
window.__console.log(this[element]);
newArray.push(callback(this[element]));
window.__console.log("elem: " + newArray);
}
window.__console.log("final: " + newArray);
return newArray;
}
elem: 46,130,196,10,NaN
final: 46,130,196,10,NaN
If you look, the final array is printing NaN because of adding the function(callback), but the strange thing is that after the line of declaring a newArray, which I am logging "this"(line 4), the function(callback) is not added. Can somebody please explain what happened and why it is added? If instead of the for loop, I add the forEach loop it works properly, only with the for loop is that it acts weirdly. (this.forEach(a => newArray.push(callback(a)));)