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