我想连续循环运行下面的程序直到我的数组长度。我希望程序像第一次输入那样运行,然后在第一次比较之后程序不应该结束,而是应该运行,直到满足for循环条件。该程序如下:如何在JavaScript中使用循环,特别是在我的程序中?
var userChoice = prompt("What would you like to select: rock, paper or scissors?");
var computerChoice = Math.random();
if(computerChoice<0.34) {
computerChoice = "rock";
}
else if(computerChoice<=0.67) {
computerChoice = "paper";
}
else if(computerChoice<=1) {
computerChoice = "scissors";
}
console.log("Computer: "+computerChoice);
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "It is a tie!";
}
else if(choice1 === rock) {
if(choice2 === paper) {
return "paper wins";
}
else {
return "rock wins";
}
}
else if(choice1 === paper) {
if(choice2 === rock) {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if(choice1 === scissors) {
if(choice2 === paper) {
return "scissors wins";
}
else {
return "rock wins";
}
}
};
compare(userChoice, computerChoice);
我的数组是:
我想它是:
var userChoice = ["rock", "paper", "scissors"];
for(i=0; i<userChoice.length; i++) {
var userChoice = prompt("What would you like to select: rock, paper or scissors?");
var computerChoice = Math.random();
if(computerChoice<0.34) {
computerChoice = "rock";
}
else if(computerChoice<=0.67) {
computerChoice = "paper";
}
else if(computerChoice<=1) {
computerChoice = "scissors";
}
console.log("Computer: "+computerChoice);
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "It is a tie!";
}
else if(choice1 === rock) {
if(choice2 === paper) {
return "paper wins";
}
else {
return "rock wins";
}
}
else if(choice1 === paper) {
if(choice2 === rock) {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if(choice1 === scissors) {
if(choice2 === paper) {
return "scissors wins";
}
else {
return "rock wins";
}
}
};
compare(userChoice, computerChoice);
}
,但它给我一个错误:不定义rock
。
提示 - 岩石是不一样的“石头” – bsoist
你还不明白什么部分错误的?你用字符串文字混淆变量吗? – SLaks
如果你想避免所有的引用,你可以做一些像“rock =”rock“; paper =“paper”;剪刀=“剪刀”' – bsoist