Home  >  Q&A  >  body text

javascript - split method of array

'1,2,3,4,5'.split(',');
The above code will output ['1','2','3','4','5'] ;
Each value in the array is of string type. Is there any good way to make the values ​​in the split array become number type?

学习ing学习ing2637 days ago997

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-06-30 09:59:12

    You can only traverse it again after splitting

    reply
    0
  • 代言

    代言2017-06-30 09:59:12

    var number = '1,2,3,5,4,9,8,7'.split(','),
        out = [];
    for(var i=0;i<number.length;i++){
        out.push(+number[i])
    }
    console.log(out)
    [1, 2, 3, 5, 4, 9, 8, 7]

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-30 09:59:12

    const a ='123456';
    a.split(' ').map (i => Number(i))

    reply
    0
  • 怪我咯

    怪我咯2017-06-30 09:59:12

    The type of your split ('1,2,3,4,5') is originally a string, just a string composed of numbers. Therefore, it is right for the array formed after split to maintain its original type. Because it is not a numeric type. To change it to number type, just iterate through the array and convert each element.

    reply
    0
  • Cancelreply