非常簡單的代碼片段(我是編程新手),我很難過。Javascript ELSE語句無論IF語句如何運行
無論IF語句是否爲真,控制檯爲什麼每次循環都會返回0?
例如,IF語句運行,找到一個匹配並將1寫入控制檯,但隨後ELSE語句也會運行,重置變量「count」。
//Snippet of the array of objects, that the program searches through
var students = [
{
name: 'Dave',
track: 'Front End Development',
achievements: 158,
points: 14730
},
{
name: 'John',
track: 'Full Stack',
achievements: '24',
points: '2450'
}
];
//Declaring variables
var message = '';
var student;
var count = 0;
var name;
var search;
while (true) {
\t search = prompt("Enter a name to see their report, or type 'quit' to exit.");
\t if (search.toUpperCase() == 'QUIT' || search.toUpperCase() == null) {
\t \t console.log(8);
\t \t break;
\t }
\t for (i = 0; i < students.length; i++) {
\t \t student = students[i];
\t \t name = search.toUpperCase();
\t \t if (name == student.name.toUpperCase()) {
\t \t \t count ++;
\t \t \t console.log(count);
\t \t } else {
\t \t \t count = 0;
\t \t \t console.log(count);
\t \t }
\t }
}
對於'name == student.name.toUpperCase()',您總是得到'false'。請寫完整的代碼,以便其他人可以幫助你。並使用'++ count;'然後'count ++' –
'name'或'student.name.toUpperCase()'其中一個返回'false'值。因此控制檯返回0.徹底調試您的代碼。 ''for'loop'外的'count'變量初始化爲0 – user61092
'students'和'name'變量的值是什麼? – madox2