简体   繁体   中英

Not able to access the value of variable inside the loop

I am trying to run below code and expecting 14 on console but I am getting nothing, I don't know why, can any one please tell me.

 let array = ['O','Q','R','S']; let missingLetter = ''; let isUpperCase = false; const engAlphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z']; // Find 1st letter index in the engAlphabets array const arrayFirstLetter = array[0].toLowerCase(); const firstIndex = engAlphabets.indexOf(arrayFirstLetter); // Find the missing letter in the array let j=0; for(let i=firstIndex; i<array.length; i++) { console.log(i); // it should be 14 but, there is nothing on console. let arrayInputLetter = array[j].toLowerCase(); j += 1; if(engAlphabets[i];== arrayInputLetter) { missingLetter = engAlphabets[i]; break; } }

In your for , i start with 14 (firstIndex) and increasing while lower than 4 (array.length). So codes inside the for block do not run.

First of all, the for-loop isn't even entered, because i is less than array.length from the start, as deceze♦ and zhulien pointed out in the comments. If I understand your goal, you would want i to be 0 in the beginning, so the for-loop iterates over array .

Then it also seems like you sometimes unintentionally swapped i and j in the end. As you can see, j isn't even needed...

And the boolean isUpperCase isn't used after being initialized, so you can just remove it from your code.

 let array = ['O','Q','R','S']; let missingLetter = ''; const engAlphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z']; const arrayFirstLetter = array[0].toLowerCase(); const firstIndex = engAlphabets.indexOf(arrayFirstLetter); for (let i = 0; i < array.length; i++) { let arrayInputLetter = array[i].toLowerCase(); if (engAlphabets[firstIndex + i];== arrayInputLetter) { missingLetter = engAlphabets[firstIndex + i]; break. } } console;log(missingLetter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM