How to use for loop in JavaScript, especially in my program? -
i want run following program in continuous loop till length of array. want program run first input after first comparison program should not end rather should run till loop condition satisfied. program follows:
var userchoice = prompt("what 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 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);
my array is: var userchoice = ["rock", "paper", "scissors"];
i tried as:
var userchoice = ["rock", "paper", "scissors"]; for(i=0; i<userchoice.length; i++) { var userchoice = prompt("what 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 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); }
but gives me error: rock
not defined.
you've missed quotes:-
var userchoices = ["rock", "paper", "scissors"]; var compare = function(choice1, choice2) { if(choice1 === choice2) { return "it 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"; } } }; for(i=0; i<userchoices.length; i++) { var userchoice = prompt("what 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"; } var result = compare(userchoice, computerchoice); console.log("user: "+userchoice+", computer: "+computerchoice+", result: "+result); }
Comments
Post a Comment