1

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

J21 B
  • 31
  • 3
  • Try to log `elem` too, it should be clearer where the problem lies **`in`** – Kaiido Mar 19 '19 at 03:22
  • You are in the third case of the [accepted answer](https://stackoverflow.com/a/500531/3702797) – Kaiido Mar 19 '19 at 03:26
  • Can anyone explain why `this[element]` does not mean value at `element` index in `this` (array)? How is it getting the value? –  Mar 19 '19 at 03:31
  • @psinaught read the duplicate question and its answers. `for(let key in array)` will iterate over all the keys of the array, not only the numeric indexes, but all its keys. So since OP has added `myMap` property to this object, it will also iterate over `"myMap"` key and `this["myMap"]` is OP's function. – Kaiido Mar 19 '19 at 03:34
  • @Kaiido, based on what your saying, if I still wanted to use the for loop for this purpose, what should I write for the code to work? Should I write : `if (typeof this[element] !== number) {...}` or what? – J21 B Mar 19 '19 at 04:38
  • If you really wish to use `for in`, that would be `if(this.hasOwnProperty(element)) { newArray.push(callback(this[element])) }` – Kaiido Mar 19 '19 at 07:02

0 Answers0