#weird parseInt behavior

31 messages · Page 1 of 1 (latest)

deep daggerBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by staff
timber spindle

What’s confusing? Strings can’t be converted to numbers. You split the string into individual characters of letters and spaces

tawdry elk

nah I understand that

but in the second command

there are numbers

where do they come from?

that's what I'm confused on

because they don't appear when using .map(e=>[])

timber spindle

What numbers?

tawdry elk

only when just doing .map(parseInt)

oh shit

timber spindle

parseInt() is returning NaN every time

tawdry elk

sorry I accidentally sent uncropped screenshot and cropped screenshot of the same thing instead of the three commands I meant to

timber spindle

Oh right haha

Errr

I’m actually interested myself as I don’t know either 💀

tawdry elk

hah

fair

my friend was doing this earlier and I looked at it like ???

what are the chances chatgpt knows

timber spindle

Maybe it’s as .map has 3 params, the value at that current index, the index, and the array itself

Ah

Says here about it with parseInt

I don’t actually know what this means currently

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. It is converted to a 32-bit integer; if it's nonzero and outside the range of [2, 36] after conversion, the function will always return NaN. If 0 or not provided, the radix will be inferred based on string's value. Be careful — this does not always default to 10! The description below explains in more detail what happens when radix is not provided.

But as map has a second param of index it also gets passed into parseInt()

shut canopy

if you want to map an array of strings to an array of numbers, use map(x => parseInt(x))/map(x => parseFloat(x))/map(x => Number(x))/map(parseFloat)/map(Number)

map(parseInt) will not work because the index of each element will be accepted as the radix; this is not an issue with parseFloat or Number because they don't accept radices.

because only integers between 2 and 36 are valid radices, you'll get the behavior that -
the first and second elements (index 0, 1) and the 38th element onward (index 37+) will always be NaN.
the third element (index 2) will be parsed as base 2
the fourth element (index 3) will be parsed as base 3
the fifth element (index 4) will be parsed as base 4
etc,
the 37th element (index 36) will be parsed as base 36