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

magnusbl picture magnusbl · Mar 28, 2012 · Viewed 164.9k times · Source

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!

Answer

Niet the Dark Absol picture Niet the Dark Absol · Mar 28, 2012

Why not just do this?

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