How to convert an integer into an array of digits

前端 未结 11 1237
别那么骄傲
别那么骄傲 2021-01-30 23:07

I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

11条回答
  •  误落风尘
    2021-01-30 23:22

    Here are the two methods I usually use for this. The first method:

    function toArr1(n) {
        "use strict";
        var sum = 0;    
        n = Array.from(String(n), Number); 
           /*even if the type of (n) was a number it will be treated as a string and will 
        convert to an Array*/
        for (i = 0; i < n.length; i += 1) {
            sum += n[i];
        }
        return sum;
    }
    

    The second method:

    function toArr2(n) {
        var sum = 0;
        n = n.toString().split('').map(Number);
        for (i = 0; i < n.length; i += 1) {
            sum += n[i]; 
        }
        return sum;
    }
    

提交回复
热议问题