Domanda

I feel like I'm doing some noobish overlooking of things. Can anyone help me understand why the following doesn't work

["1.1", "2.2", "3.3"].map(parseInt);
//=> [1, NaN, NaN]

This works though ???

["1.1", "2.2", "3.3"].map(function(num) {
  return parseInt(num);
});
//=> [1, 2, 3]

This seems to work too

["1.1", "2.2", "3.3"].map(Number);
//=> [1.1, 2.2, 3.3]
È stato utile?

Soluzione

Array.prototype.map passes more than one arguments to the callback. In particular the second argument it passes is the index of the element being processed.

parseInt accepts more than one argument. In particular the second argument it accepts is the base of the numeric system you are converting from.

When the second element is processed you are calling parseInt("2.2", 1), and since 2 is not a valid digit in base 1 the result is NaN.

If you declare a "wrapper" callback around parseInt then these additional arguments are lost and everything seems to work correctly, although you should always pass the second argument to parseInt.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top