javascriptarraysdigits

How do I separate an integer into separate digits in an array in JavaScript?


This is my code so far:

var n = 123456789;
var d = n.toString().length;
var digits = [];
var squaredDigits = [];
for (i = d; i >= 1; i--) {
    var j = k / 10;
    var r = (n % k / j) - 0.5;
    var k = Math.pow(10, i);
    var result = r.toFixed(); 
    digits.push(result);
}

console.log(digits);

But when I run my code I get this: [9, 1, 2, 3, 4, 5, 6, 7, 8]

If anyone can see the problem or find a better solution I would very much appreciate it!


Solution

  • Why not just do this?

    var n =  123456789;
    var digits = (""+n).split("");