Jiang Yuxin
Jiang Yuxin

Reputation: 381

Split a number to individual digits in javascript using basic methods

var count = 0;
var arr = [];

function Split(number) {
  if (Math.floor(number / 10) > 0) {
    for (var count = 0; count < number.toString().length; count++)
      arr[count] = number % 10;
    number = Math.floor(number / 10);
  }
  return arr;
}
document.write(Split(2345))

It's returning 5,5,5,5 while I expected the result to be 2,3,4,5 Please tell me what part went wrong. Thank you!

Upvotes: 0

Views: 82

Answers (1)

RobG
RobG

Reputation: 147363

Your error is here:

for (var count = 0; count < number.toString().length; count++)
  arr[count] = number % 10;
number = Math.floor(number / 10);

Only the first statement is included in the for loop, the second only runs after the for loop ends. You need braces around both statements so both run on each iteration.

for (var count = 0; count < number.toString().length; count++) {
  arr[count] = number % 10;
  number = Math.floor(number / 10);
}

But you'll still get the wrong result because you reset the limit for count on each iteration. Set it once at the start.

var count = 0;
var arr = [];

function Split(number) {
  if (Math.floor(number / 10) > 0) {
    for (var count = 0, countLen = number.toString().length; count < countLen; count++) {
      arr[count] = number % 10;
      number = Math.floor(number / 10);
    }
  }
  return arr;
}
document.write(Split(2345));

Upvotes: 1

Related Questions