[英]If-statement fail in javascript
For several hours now am I trying to make a simple game, but one if-statement is failing: 现在几个小时我想做一个简单的游戏,但是一个if语句失败了:
function checkDiagonaal() {
if (document.getElementById("11").src.indexOf("o.png") &&
document.getElementById("22").src.indexOf("x.png") &&
document.getElementById("33").src.indexOf("o.png"))
{
winnaar = true;
}
}
The condition is not true, yet the variable winnaar
is set on true
. 条件不正确,但变量
winnaar
设置为true
。 I don't see what I am doing wrong. 我不明白我做错了什么。 Very probably just a little mistake.
很可能只是一个小错误。
I also tried this code: 我也试过这段代码:
if(document.getElementById("11").src === "images/o.png")
but this returns false (even when the condition is true). 但这会返回false(即使条件为真)。 I would like to know why?
我想知道为什么?
在这种情况下使用...indexOf(...) >= 0
。
当找不到值时,indexOf返回-1,-1是真的
From the MDN (great resource!): 来自MDN (很棒的资源!):
"The indexOf() method returns the index within the calling String object of the first occurrence of the specified value [...] returns -1 if the value is not found."
“indexOf()方法返回指定值第一次出现的调用String对象中的索引[...]如果找不到值,则返回-1 。”
When statements get big they become a bit unreadable, it might be fine now, but if you need to add more checks, I would suggest a different approach: 当语句变大时,它们变得有点难以理解,现在可能没问题,但是如果你需要添加更多的检查,我建议采用不同的方法:
function checkDiagonaal() {
var ids = [11,22,33];
var strs = ['o.png','x.png','o.png'];
var winnar = ids.every(function(id,i) {
return document.getElementById(id).src.indexOf(strs[i]) > -1;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.