为什么此警报不在if语句中执行

时间:2015-10-22 07:37:48

标签: javascript if-statement while-loop

此程序应在第4次迭代中显示警告Found it

var animals = ["horse", "ox", "cow", "pig", "duck"];  
var i = 0;  
while (i < animals.length) {  
  if (animals.slice(i, i + 1) === "pig") {  
      alert("Found it");  
      break;  
  }  
 i++;  
}  

2 个答案:

答案 0 :(得分:2)

animals.slice在将其与字符串进行比较时返回一个数组。试试:

if (animals[i] === "pig") {}

答案 1 :(得分:2)

var animals=["horse", "ox", "cow", "pig", "duck"];  
var i = 0;  
while (i < animals.length) {  
  if (animals[i] = "pig") {  
      alert("Found it");  
      break;  
  }  
 i++;  
}

这将解决您的问题。不要在代码中使用slice