无论IF语句如何,Javascript ELSE语句都会运行

时间:2016-01-16 10:57:14

标签: javascript if-statement for-loop

非常简单的代码片段(我是编程新手),而且我很难过。

为什么控制台在循环中每次迭代都返回0,无论IF语句是否为真?

例如,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) {
	search = prompt("Enter a name to see their report, or type 'quit' to exit.");
	if (search.toUpperCase() == 'QUIT' || search.toUpperCase() == null) {
		console.log(8);
		break;
	}
	for (i = 0; i < students.length; i++) {
		student = students[i];
		name = search.toUpperCase();
		if (name == student.name.toUpperCase()) {
			count ++;
			console.log(count);
		} else {
			count = 0;
			console.log(count);
		}
	}
}
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

count = 0;移到for loop之外。刚开始是一个空柜台。

答案 1 :(得分:0)

我无法立即看到您问题的原因,count = 0分支中else的重置看起来不对,如果重复名称会导致问题,但您至少应该在第一次匹配时获得1次,而您断言它始终返回0

无论哪种方式,更为惯用的写作方式是:

var uSearch = search.toUpperCase();
var count = students.filter(function(student) {
    return student.name.toUpperCase() === uSearch;
}).length;

答案 2 :(得分:0)

是的,正如Matt所说......你可以先在循环外初始化count = 0。在条件出现之前,我还要抓一条线console.log(name)

count = 0
for (i = 0; i < students.length; i++) {
  student = students[i];
  name = search.toUpperCase();

  # show me the "name" before running condition
  console.log("name pulled from search: ",name)

  if (name == student.name.toUpperCase()) {
    count++;
    console.log(count);
  } else {
    count = 0;
    console.log(count);
  }
}

打印"name"可以让您了解条件是如何匹配的。

答案 3 :(得分:-1)

这是用于比较两个数组的值的示例代码。

   var count = 0;

var students = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];   

var search = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 3", value:"this", other: "that" }
]; 

for (var i = 0; i < students.length; i++) {

for (var j = 0; j < search.length; j++) {

    var student = students[i].name.toUpperCase();

  var names = search[j].name.toUpperCase();

  if (names == student) {
    count++;

    console.log(count);
  } else {
    count = 0;

    console.log(count);
  }
  }
}