我希望循环运行到提示符的值,但它是无限的。需要帮助。以下是我的javascript代码:我的代码
var round = prompt("enter text");
var roundno = round;
var images_arr = ["../img/paper.png", "../img/stone.png", "../img/sisor.png"];
var size = images_arr.length
function myFunction() {
for (var i = 0; i = roundno; i + 1) {
console.log(i);
setInterval(function () {
var x = Math.floor(size * Math.random())
$('#random').attr('src', images_arr[x]);
}, 1500);
setInterval(function () {
var sound = new Audio("../audio/audio.mp3");
sound.play();
}, 3000);
if (i = roundno) {
break;
}
}
}发布于 2020-06-20 11:24:07
您的代码有很多问题。
var round = prompt("enter text"); // how do you know the user enters a number?
var defaultNumberOfRounds = 1; // I added this row
// CHANGED THIS IN EDIT
var roundno = round; // should be: isNaN(Number(round)) ? defaultNumberOfRounds : round
var images_arr = ["../img/paper.png", "../img/stone.png", "../img/sisor.png"];
var size = images_arr.length
function myFunction() {
// CHANGED THIS IN EDIT the conditions within () should be: var i = 0; i < roundno; i++
for (var i = 0; i = roundno; i + 1) {
console.log(i);
// all iterations in the loop will execute this at the same time.
setInterval(function () {
var x = Math.floor(size * Math.random())
$('#random').attr('src', images_arr[x]); // JQuery
}, 1500);
// all iterations in the loop will execute this at the same time.
setInterval(function () {
var sound = new Audio("../audio/audio.mp3");
sound.play();
}, 3000);
if (i = roundno) { // should be i == roundno
break; // don't need to break it, because your for loop's condition should take care of this
}
}
}
} // ADDED THIS IN EDIT: missing curly bracket编辑:我添加了一个代码段,以显示我的代码正在工作。我注释了for循环中的所有代码,并且必须更改声明roundno和for循环中的语句。
var round = prompt("enter text");
var defaultNumberOfRounds = 1;
var roundno = isNaN(Number(round)) ? defaultNumberOfRounds : round;
var images_arr = ["../img/paper.png", "../img/stone.png", "../img/sisor.png"];
var size = images_arr.length;
console.log(`round: ${round}, roundno: ${roundno}`);
function myFunction() {
for (var i = 0; i < roundno; i++) {
console.log(i);
/*setInterval(function () {
var x = Math.floor(size * Math.random())
$('#random').attr('src', images_arr[x]); // JQuery
}, 1500);
setInterval(function () {
var sound = new Audio("../audio/audio.mp3");
sound.play();
}, 3000);*/
}
}
myFunction();
发布于 2020-06-20 11:14:50
您没有递增i
变化
i + 1致下列之一:
i++i += 1i = i + 1此外,您还需要修复循环末尾的if语句。您希望检查i是否等于roundno。不要使用赋值操作符= (将roundno的值赋值给i ),而是使用==或===进行等式检查。
if (i == roundno) {
break;
}您也在循环条件下输入了相同的错误。将循环条件更改为i == roundno,并在循环结束时删除if语句,因为在循环条件固定后,循环中的if语句是不必要的。
for (var i = 0; i == roundno; i++) {
// code
}https://stackoverflow.com/questions/62485046
复制相似问题