简体   繁体   English

无法访问循环内变量的值

[英]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.我试图在代码下方运行并期望在控制台上运行 14 但我什么也没得到,我不知道为什么,谁能告诉我。

 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).在你的for 中从 14(firstIndex)开始并在低于 4(array.length)时增加。 So codes inside the for block do not run.因此for块内的代码不会运行。

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.首先,甚至没有输入 for 循环,因为i从一开始就小于array.length ,正如deceze♦zulien在评论中指出的那样。 If I understand your goal, you would want i to be 0 in the beginning, so the for-loop iterates over array .如果我理解您的目标,您会希望i开始为0 ,因此 for 循环遍历array

Then it also seems like you sometimes unintentionally swapped i and j in the end.然后,您似乎有时最终会无意中交换ij As you can see, j isn't even needed...如您所见,甚至不需要j ...

And the boolean isUpperCase isn't used after being initialized, so you can just remove it from your code.并且 boolean isUpperCase初始化后不使用,因此您可以将其从代码中删除。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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