0

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!

8
  • 1
    document.write( (2345).toString().split("") ); Commented Oct 10, 2019 at 1:52
  • (number).toString() converts the number into string representation. string.split("") splits the string into an array, passing a blank delimiter "" splits the string into individual characters. Commented Oct 10, 2019 at 1:57
  • Can you please explain your own algorithm in English? What exactly is your approach? Commented Oct 10, 2019 at 1:58
  • Why Math.floor(number / 10) > 0 rather than the much simpler number > 10? Commented Oct 10, 2019 at 1:58
  • @Synthetx But this approach is not using the function I wrote? Sorry I am really confused but it seems like I don't need the function to display 2,3,4,5 by your approach Commented Oct 10, 2019 at 2:01

1 Answer 1

1

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));

Sign up to request clarification or add additional context in comments.

6 Comments

hum rather : for (var count = number.toString().length; count > 0; count--)
Thank you. May I ask what does countLen mean? Is Len a method? (Sorry if the question is stupid I
@JiangYuxin no it is not a method, it is a variable that is set to the length of the number.toString()
Sorry I still don't get it. If number changes in the loop won't every variable involved number be changed automatically?
@SimonDehaut—yes, I was trying to keep close to the OP. :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.