How to convert a string of numbers to an array of numbers?

前端 未结 15 1953
死守一世寂寞
死守一世寂寞 2020-11-27 10:29

I have below string -

var a = \"1,2,3,4\";

when I do -

var b = a.split(\',\');

I get b as

相关标签:
15条回答
  • 2020-11-27 10:41

    Array.from() for details go to MDN

    var a = "1,2,3,4";
    var b = Array.from(a.split(','),Number);
    

    b is an array of numbers

    0 讨论(0)
  • 2020-11-27 10:42

    The underscore js way -

    var a = "1,2,3,4",
      b = a.split(',');
    
    //remove falsy/empty values from array after split
    b = _.compact(b);
    //then Convert array of string values into Integer
    b = _.map(b, Number);
    
    console.log('Log String to Int conversion @b =', b);
    
    0 讨论(0)
  • 2020-11-27 10:45

    Since all the answers allow NaN to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.

    var a = "1,2,3,4,foo,bar";
    
    var b = a.split(',');
    
    var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
    
    // or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
    
    0 讨论(0)
  • 2020-11-27 10:48

    My 2 cents for golfers:

    b="1,2,3,4".split`,`.map(x=>+x)
    

    backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :

    function(x){return parseInt(x,10)}// version from techfoobar
    (x)=>{return parseInt(x)}         // lambda are shorter and parseInt default is 10
    (x)=>{return +x}                  // diff. with parseInt in SO but + is better in this case
    x=>+x                             // no multiple args, just 1 function call
    

    I hope it is a bit more clear.

    0 讨论(0)
  • 2020-11-27 10:48

    You can use Array.map to convert each element into a number.

    var a = "1,2,3,4";
    
    var b = a.split(',').map(function(item) {
        return parseInt(item, 10);
    });
    

    Check the Docs


    Or more elegantly as pointed out by User: thg435

    var b = a.split(',').map(Number);
    

    Where Number() would do the rest:check here


    Note: For older browsers that don't support map, you can add an implementation yourself like:

    Array.prototype.map = Array.prototype.map || function(_x) {
        for(var o=[], i=0; i<this.length; i++) { 
            o[i] = _x(this[i]); 
        }
        return o;
    };
    
    0 讨论(0)
  • 2020-11-27 10:48

    Map it to integers:

    a.split(',').map(function(i){
        return parseInt(i, 10);
    })
    

    map looks at every array item, passes it to the function provided and returns an array with the return values of that function. map isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.

    Or, if you prefer loops:

    var res = a.split(",");
    for (var i=0; i<res.length; i++)
    {
        res[i] = parseInt(res[i], 10);
    }
    
    0 讨论(0)
提交回复
热议问题