Javascript _.map () vs array.map (); why does one work here and not the other?

Why does reverse2 function using _.map () work, but arr.map () does not work in this situation? Is there a syntax problem? I could not figure it out.

function reverse2(arr){ return _.map(arr, function(val,index, arr1){return arr1.pop();}); } console.log(reverse2([1,2,3,4,5,6])); // logs [6,5,4,3,2,1] function reverse3(arr){ return arr.map(function(val,index, arr1){return arr1.pop();}); } console.log(reverse3([1,2,3,4,5,6])); // logs [6,5,4,undefined, undefined, undefined] 
+5
source share
2 answers

Array.prototype.map

This is a difficult question. To explain why Array.prototype.map behaves this way, we need to check the spec . So:

  • Let O be the result of calling ToObject, passing the value of this as an argument.
  • Let lenValue be the result of calling the [[Get]] O internal method with argument length ".
  • Let len ​​- ToUint32 (lenValue).
  • If IsCallable (callbackfn) is false , throw a TypeError exception.
  • If thisArg was provided, let T be Arg; otherwise let T be undefined .
  • Let A be a new array, created as if the expression new Array (len) , where Array is the standard built-in constructor with this name, and len is the value of len. ...

The important points here are # 2 and # 6. From them it is obvious that map creates a new array with the same length as the original one.

Then one more thing from the same section about the method:

... If the existing elements of the array are changed, their value passed to callbackfn will be the value that visits them on the time map; items that are deleted after calling the card , and before they are visited are not visited.

And it gives an answer to your question: the map will create an array of the same length, but since in the iteration function you delete elements from the original array (using pop ), the new array is filled only with the second half of the original.

_. Map

Why does the underscore _.map function behave differently? Since its implementation iterates over all elements of the original array. Hence the difference.

+5
source
 array.map first call: [1,2,3,4,5,6], position 0 hash value '1', so pop 6. seconde call: [1,2,3,4,5], position 1 hash value '2', so pop 5. third call: [1,2,3,4], position 2 hash value '3', so pop 4. fourth call: [1,2,3], position 3 hash no value, so pop nothing. 
0
source

All Articles