function calculateBinary(bits) {
var bitValue = 0;
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if (bits[1] === '1') {
bitValue += 64;
} else if (bits[2] === '1') {
bitValue += 32;
} else if (bits[3] === '1') {
bitValue += 16;
} else if (bits[4] === '1') {
bitValue += 8;
} else if (bits[5] === '1') {
bitValue += 4;
} else if (bits[6] === '1') {
bitValue += 2;
} else if (bits[7] === '1') {
bitValue += 1;
}
}
return bitValue;
}
calculateBinary('11111111');
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Why is my for loop treating every iteration of the bits string as bits[0]? The returned value is '1028' or 12 * 8. What am I doing wrong to cause this in my For loop?