The mapping passes three arguments to its function:
- the element;
- the index of that element within the array; and
- the array itself.
The parseInt
function will look at the first two of those, treating the first correctly as the string but treating the second as the base to use. When the base is neither zero nor in the inclusive range 2..36
, it returns NaN
(1). If you had an array with forty elements, you'd also see a bunch of NaN
values at the end:
0, NaN, 0, 0, 0, ... 0, 0, 0, NaN, NaN
You'd also get some pretty strange results if the number strings were anything other than zero, since the array index would dictate what base was used to interpret it.
To actually fix this, you can just provide a function that will translate what map
gives you to what parseInt
expects (a map map, I guess you could call it):
function myParseInt(s,r,a) { return parseInt(s,10); }
var arr = new Array(32).join(0).split('').map(myParseInt)
alert(arr)
You might also want to have a look at the way you're creating this array, it will actually end up as an array of size 31 rather than 32. If you just want an array of '0'
characters, you can just use:
var arr = new Array(32).fill('0')
assuming you have a browser that supports ECMAScript 2015, which is Safari, Firefox and Chrome-desktop as of the time of this answer.
(1) A base of zero is the default case for handling things like hex prefixes.
A base of one makes no sense in a purely positional system (where each digit is multiplied by a power of the base and accumulated) since the only allowed digit there would be 0
, so each place value would be that zero multiplied by 1n
. In other words, the only number possible in a base-one system would be zero.
Bases from 2
to 36
are therefore more sensible.