How to change value of my array if I've got ["-2", -1, 0, 1, 2]. I take data from text box, i need to have array of int instead of this with one string at the begining. I tried parseInt(array) and eval(array) but nothing is working. Thanks
5 Answers
You don't parse whole arrays, just elements from them. In your case parseInt(array[0]). This will parse an element at position 0 from your array (your first element).
EDIT:
Parsing to other number systems:
// Numbers with a leading 0 use a radix of 8 (octal)
var example = parseInt('0101');
// Numbers that start with 0x use a radix of 16 (hexidecimal)
var example = parseInt('0x0101');
// Numbers starting with anything else assumes a radix of 10
var example = parseInt('101');
// Or you can specify the radix, in this case 2 (binary)
var example = parseInt('0101', 2);
SOURCE: http://www.apkapps.link/questions/810611/why-do-we-need-to-use-radix
Comments
If you just want to make sure everything is numeric you can map everything to the Number() function:
[-1,0,1,3,4].map(Number)
However, that will leave "1.23" as 1.23.
To turn everything to INTs you cannot just map everything to parseInt() directly because map will actually pass multiple parameters and parseInt will use the extra paramenters to [incorrectly] define the radix. To make it work with parseInt you need to return a new function that calls parse with just the first parameter:
function mapParseInt(x) {
return parseInt(x,10);
}
["-2", -1, 0, 1, 2.2].map(mapParseInt);
Or with an ES2015 fat arrow function:
["-2", -1, 0, 1, 2.2].map( x => parseInt(x,10) )
Comments
To turn everything to INTs you cannot just map everything to parseInt() directly because map will actually pass multiple parameters and parseInt will use the extra paramenters to [incorrectly] define the radix. To make it work with parseInt you need to return a new function that calls parse with just the first parameter: http://www.azar.in/questions/810611/why-do-we-need-to-use-radix
array[0] = +array[0];["-2", -1, 0, 1, 2].map(Number)