How to convert all elements in an array to integer in JavaScript?

前端 未结 11 1501
生来不讨喜
生来不讨喜 2020-12-07 14:47

I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = \'         


        
11条回答
  •  渐次进展
    2020-12-07 15:15

    const arrString = ["1","2","3","4","5"];
    const arrInteger = arrString.map(x => Number.parseInt(x, 10));
    

    Above one should be simple enough,

    One tricky part is when you try to use point free function for map as below

    const arrString = ["1","2","3","4","5"];
    const arrInteger = arrString.map(Number.parseInt);
    

    In this case, result will be [1, NaN, NaN, NaN, NaN] since function argument signature for map and parseInt differs

    map expects - (value, index, array) where as parseInt expects - (value, radix)

提交回复
热议问题