Node: Array.prototype.map unexpected behaviour with parseInt

Created on 9 Apr 2017  路  4Comments  路  Source: nodejs/node

  • Version: v7.8.0
  • Platform: Linux brainstorm3 4.4.0-72-generic #93-Ubuntu SMP Fri Mar 31 14:07:41 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem:

perhaps, I've found interpreter bug. I can reproduce them on Chromium 57.0.2987.98 and on node 6.10.0

I need filter number in array, so I did the following:

[ 134, 135, 1212, 33 ].map(parseInt);

So the result was following:

[ 134, NaN, 1, NaN ]

This is not correct behaviour of Array.prototype.map or parseInt or interpreter.
This code works corect:

[ 134, 135, 1212, 33 ].map((item)=>parseInt(item) );
invalid

Most helpful comment

This is because map is calling parseInt with two arguments: the element and the index. The index ends up being used as the radix. So, this is what's happening:

parseInt(134, 0) // => 134
parseInt(135, 1) // => NaN
parseInt(1212, 2) // => 1
parseInt(33, 3) // => NaN

_edit_: posted too early :p

All 4 comments

This is because map is calling parseInt with two arguments: the element and the index. The index ends up being used as the radix. So, this is what's happening:

parseInt(134, 0) // => 134
parseInt(135, 1) // => NaN
parseInt(1212, 2) // => 1
parseInt(33, 3) // => NaN

_edit_: posted too early :p

sorry this is not a bug.

@Ilya1st yeah, it's not a bug, just a common mistake many people (especially beginners) do :)
But if you ever actually find an bug in V8, feel free to submit it directly to the V8 issue tracker. Thanks!

@aqrln yes this is just about too much coding this week :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sandeepks1 picture sandeepks1  路  3Comments

seishun picture seishun  路  3Comments

stevenvachon picture stevenvachon  路  3Comments

addaleax picture addaleax  路  3Comments

dfahlander picture dfahlander  路  3Comments