我有一个简单的问题,我不确定为什么数组内容没有正确返回。我很确定这很简单,但是以某种方式我没有得到想要的结果。场景是将变量“比较”设置为一个值,例如“ apple”,然后我循环到数组中,如果apple与索引匹配,则将其打印到文本字段中。它不会这样做,并且总是说“不一样”的值。对于有价值的狗,它的工作原理。似乎到达了最后一个数组然后进行了比较。请帮忙。
下面的代码
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {text = "The value is " + arr[i] + "<br>"; }
else if (compare == "" || compare == null) { text = "The value is blank"; }
else if (arr[i] != compare) {text = "not the same"; }
else {text ="some error";}
}
document.getElementById("demo").innerHTML = text;
}
</script>
<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
function print(msg) {
document.getElementById("demo").innerHTML += msg + '</br>';
}
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = document.getElementById('compare').value;
if (!compare) {
print('Compare is empty');
return;
} else {
print('Comparing with ' + compare);
}
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {
print("The value is at index " + i + " is " + arr[i]);
return; //results found, break out of the for loop
} else if (arr[i] != compare) {
print("not the same");
} else {
print("some error");
}
}
print("Could not find " + compare + " in array");
}
<!DOCTYPE html>
<html>
<body>
<script>
</script>
<p>Click the button to do a loop with a break.</p>
<input type="text" id="compare" placeholder="Compare to" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
出于性能原因,最好compare
在循环开始之前验证的值。您可以使用破环了break
,continue
或者return
关键字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句