Home > OS >  How can I create a loop for string symbols?
How can I create a loop for string symbols?

Time:12-17

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.

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

CodePudding user response:

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

CodePudding user response:

At the first you can change string to an array after that you can use from reduce() method.

let x = '12345';
let arr = x.split('');

  const total = arr.reduce(function (acc, value, i, arr) {
      return acc   Number(value);
}, 0);

console.log(total);

I hope it helps you!

  • Related