convert string into array of integers

后端 未结 11 1670
刺人心
刺人心 2020-11-30 19:32

I want to convert the following string \'14 2\' into an array of two integers. How can I do it ?

相关标签:
11条回答
  • 2020-11-30 19:44

    A quick one for modern browsers:

    '14 2'.split(' ').map(Number);
    
    // [14, 2]`
    
    0 讨论(0)
  • 2020-11-30 19:44
    let idsArray = ids.split(',').map((x) => parseInt(x));
    
    0 讨论(0)
  • 2020-11-30 19:47

    Better one line solution:

    var answerInt = [];
    var answerString = "1 2 3 4";
    answerString.split(' ').forEach(function (item) {
       answerInt.push(parseInt(item))
    });
    
    0 讨论(0)
  • 2020-11-30 19:51

    SO...older thread, I know, but...

    EDIT

    @RoccoMusolino had a nice catch; here's an alternative:

    TL;DR:

     const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]
    

    WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]

    There is a subtle flaw in the more elegant solutions listed here, specifically @amillara and @Marcus' otherwise beautiful answers.

    The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...

    The problem:


    var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]
    

    Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/


    The (slightly-less-baller) fix:


    var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]
    

    So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...

    Hope it saves someone time!

    0 讨论(0)
  • 2020-11-30 19:53

    You can .split() to get an array of strings, then loop through to convert them to numbers, like this:

    var myArray = "14 2".split(" ");
    for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; } 
    //use myArray, it's an array of numbers
    

    The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:

    for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); } 
    
    0 讨论(0)
  • 2020-11-30 19:58
    var result = "14 2".split(" ").map(function(x){return parseInt(x)});
    
    0 讨论(0)
提交回复
热议问题