Javascript ELSE statement running regardless of IF statement -
very simple snippet of code (i'm new programming), , i'm stumped.
why console returning 0 each iteration through loop, regardless of whether if statement true or not?
for example, if statement runs, finds match , writes 1 console, else statement runs too, resetting variable "count".
//snippet of array of objects, 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) { search = prompt("enter name see report, or type 'quit' exit."); if (search.touppercase() == 'quit' || search.touppercase() == null) { console.log(8); break; } for (i = 0; < students.length; i++) { student = students[i]; name = search.touppercase(); if (name == student.name.touppercase()) { count ++; console.log(count); } else { count = 0; console.log(count); } } }
i can't see cause of problem, reset of count = 0
in else
branch looks wrong , cause problems if name repeated, should @ least 1
once on first match, whereas assert returns 0
.
either way, more idiomatic way of writing be:
var usearch = search.touppercase(); var count = students.filter(function(student) { return student.name.touppercase() === usearch; }).length;
Comments
Post a Comment