How to convert an integer into an array of digits

前端 未结 11 1238
别那么骄傲
别那么骄傲 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:28

    The solutions proposed work fine in most cases but not with negative numbers.

    There is a solution for such cases.

    const intToArray = (int) => {
      return String(int).match(/-?\d/g).map(Number)
    }
    
    console.log(intToArray(312)) // [3, 1, 2]
    console.log(intToArray(-312)) // [-3, 1, 2]

提交回复
热议问题