在《Beginning javascript》一书中,我遇到了一个简单的程序,如下所示。我无法理解这个/那个代码如何在这里工作以及 while 循环如何在这里运行(我知道 while 循环一点,但是 != - 1 部分让它变得困惑&我所做的谷歌搜索结果有点模糊)。感谢任何帮助,如果有任何错误,请随时纠正。我可以理解下面的代码在做什么,但上面的查询仍然有点令人困惑 下面的简单代码正在运行。
代码:
var myImages = new Array("monkeyDluffy.png", "roronoaZoro.jpg", "sanji.jpg", "godUssop.png");
function changeImg(that) { //Can be named anything that is just professional
var newImgNumber = Math.round(Math.random() * 3); //a simple random number generated
while (that.src.indexOf(myImages[newImgNumber]) != -1) {
newImgNumber = Math.round(Math.random() * 3);
}
that.src = myImages[newImgNumber];
return false;
}
/*here use of this and that enables the code to perform better for a single object as*/
<html>
<head>
<title>JS</title>
<body>
<img src="monkeyDluffy.png" onclick="return changeImg(this)" />
<img src="roronoaZoro.jpg" onclick="return changeImg(this)" />
</body>
</head>
</html>
最佳答案
the != - 1 part makes it confusing
看看the documentation for indexOf
:
Return value
The index of the first occurrence of the specified value; -1 if not found.
因此它会在找到指定值时循环。当没有找到时,循环停止。
关于javascript - Javascript 中的简单 while 循环查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42534205/