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

前端 未结 11 1405
生来不讨喜
生来不讨喜 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:00

    How about this:

    let x = [1,2,3,4,5]
    let num = +x.join("")
    
    0 讨论(0)
  • 2020-12-07 15:11

    You can do

    var arrayOfNumbers = arrayOfStrings.map(Number);
    
    • MDN Array.prototype.map

    For older browsers which do not support Array.map, you can use Underscore

    var arrayOfNumbers = _.map(arrayOfStrings, Number);
    
    0 讨论(0)
  • 2020-12-07 15:15

    var arr = ["1", "2", "3"];
    arr = arr.map(Number);
    console.log(arr); // [1, 2, 3]

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-07 15:18

    You need to loop through and parse/convert the elements in your array, like this:

    var result_string = 'a,b,c,d|1,2,3,4',
        result = result_string.split("|"),
        alpha = result[0],
        count = result[1],
        count_array = count.split(",");
    for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
    //now count_array contains numbers
    

    You can test it out here. If the +, is throwing, think of it as:

    for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
    
    0 讨论(0)
  • 2020-12-07 15:18

    Using jQuery, you can like the map() method like so;

     $.map(arr, function(val,i) { 
         return parseInt(val); 
     });
    
    0 讨论(0)
提交回复
热议问题