let a = '254';
let b = 0;
for ( let i=0 ; i< a.length-1 ; i++ ) {
b += a[i];
}
b results to ‘025’ not 11, why ?
this is don in the chrome dev tools.
let a = '254';
let b = 0;
for ( let i=0 ; i< a.length-1 ; i++ ) {
b += a[i];
}
b results to ‘025’ not 11, why ?
this is don in the chrome dev tools.
Two issues. One is that your upper limit in the for-loop is wrong and not taking the last index from a
.
Second is, that a
is a string and JS decided to turn 0 from b
into a string and thus adds the other characters from a
to it. You want to cast the characters to integers so JS knows to add numbers there.
the first issue was a common mistake i do sometimes, but the second issue’s explination is helpful thank you.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.