javascript split string to array of int

后端 未结 5 1038
时光说笑
时光说笑 2020-12-09 07:33

I have a string that\'s on the page and from which I want an array of int.

2,3,0,43,23,53

I\'m writin

相关标签:
5条回答
  • 2020-12-09 08:03
    var ArrayData = $.map($('#TheData').text().split(','), function(value){
        return parseInt(value, 10);
        // or return +value; which handles float values as well
    });
    

    You can use $.map to transform the array of strings to ints by calling parseInt on each of the elements in the array

    0 讨论(0)
  • 2020-12-09 08:07
    var ArrayData = $('#TheData').html().split(',').map( Number );
    

    Add Array.prototype.map() to older browsers with the code from MDN.


    You can use jQuery's $.map() in the same manner, though it won't work with $.prototype.map().

    var ArrayData = $.map( $('#TheData').html().split(','), Number );
    
    0 讨论(0)
  • 2020-12-09 08:10
    var ArrayData = $('#TheData').text().split(',').map(Number);
    

    You can find more here:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    0 讨论(0)
  • 2020-12-09 08:17

    Pure Javascript solution:

    const elementText = document.getElementById('divSourceID').innerText;
    const numericList = elementText.split(',').map(Number);
    

    For more information:

    1. getElementById: "The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. (...)". Source: developer.mozilla.org.

    2. Array.prototype.map: "The map() method creates a new array populated with the results of calling a provided function on every element in the calling array". Source: developer.mozilla.org.

    3. array.map(Number): This call means the first received argument will be automatically converted into number and results in the same as if you explicitly declare the arrow function:

    const numericList = elementText.split(',').map(Number);
    

    same result as:

    const numericList = elementText.split(',').map(str => Number(str));
    

    JIT: Special thanks to @Robbendebiene for the excellent code review, simplifying the previous code.

    0 讨论(0)
  • 2020-12-09 08:19

    Here is a simple answer

    let x = "1,2,3,4";
    
    let result = x.split(",").map((e) => parseInt(e));
    
    console.log(result);
    
    0 讨论(0)
提交回复
热议问题