Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a loop for string symbols?

I have a variable with string let x = '12345';. I need to find the sum of the digits of this number,
so I used Number() function to change the type.

Now I have this peace of code:

for (let i = 0; i < 5; i++){
  let o = Number(x[i]) + Number(x[x+1]);
  console.log(o);
}

I know that it’s wrong code, so I need help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to solve this question with for-loop and I don’t know how to sum the symbols of the x variable.

>Solution :

The loop should look at 1 character at-a-time and add it to an accumulating value declared outside the loop. Log the result after the loop completes.

Example with for-loop:

let x = "12345";

let total = 0;
for (let i = 0; i < x.length; i++) {
  total += Number(x[i]);
};
console.log(total);

Various looping examples:

let x = "12345";

let forLoopTotal = 0;
for (let i = 0; i < x.length; i++) {
  forLoopTotal += Number(x[i]);
}
console.log({ forLoopTotal });

let forOfTotal = 0;
for (let c of x) {
  forOfTotal += Number(c);
}
console.log({ forOfTotal });

let reduceTotal = Array.from(x).reduce((total, c) => total + Number(c), 0);
console.log({ reduceTotal });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading