Brosuke Brosuke - 1 month ago 7
Javascript Question

For loop through array.length only executes once

The code below only executes through the first 'for' loop once, yet all the other 'for' loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.

var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i=0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i=0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i=0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i=1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i=0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i]*2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i=0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum%10 == 0) {
console.log('Yes');
}
else console.log('No');
}

Answer

In your code you are using same instance of 'i' variable to iterate all loops.

Solution is to use different index variables to iterate external and internal loops

var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
    var current = numbers[j];
    /...
}

JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)

Comments