var userChoice = prompt("Do you choose rock, paper or scissors?"); var choice = ["rock", "paper", "scissors"]; if (userChoice !== choice[0]) { confirm("You must choose between rock, paper or scissors!"); }; var computerChoice = Math.random(); if (computerChoice < 0.34) { computerChoice = choice[0]; } else if(computerChoice <= 0.67) { computerChoice = choice[1]; } else { computerChoice = choice[2]; } console.log("Computer: " + computerChoice); var compare = function(choice1, choice2) { if (choice1 === choice2) { return "The result is a tie!"; } else if(choice1 === choice[0]) { if(choice2 === choice[2]) { return "rock wins"; } else { return "paper wins"; } } else if(choice1 === choice[1]) { if(choice2 === choice[0]) { return "paper wins"; } else { return "scissors wins"; } } else if(choice1 === choice[2]) { if(choice2 === choice[1]) { return "scissors wins"; } else { return "rock wins"; } } }; compare(userChoice, computerChoice); Saya telah membuat coding seperti diatas, saya ingin agar coding bisa mengeluarkan peringantan "You can only choose between rock, paper or scissors!" ketikan user memasukan input selain paper, rock atau scissors. Bagaimana caranya ya? lalu saya juga tidak ingin fungsi 'compare' berjalan jika input yang dimasukkan tidak benar, bagaimana caranya?
1 jempol
bramanto
300
1157
·
8 tahun yang lalu
·
0 jempol
Halo coder @hirahorc. Untuk melakukan validasi input bisa dibuat seperti ini : var userChoice = prompt("Do you choose rock, paper or scissors?"); var choice = ["rock", "paper", "scissors"]; // Convert to lowecase userChoice = userChoice.toLowerCase(); // Remove space userChoice = userChoice.trim(); // Create Function var keyExists = function(key, search) { if (!search || (search.constructor !== Array && search.constructor !== Object)) { return false; } for (var i = 0; i < search.length; i++) { if (search[i] === key) { return true; } } return key in search; } // Validation if(keyExists(userChoice, choice)){ // If existing } else { // No existing } Sebagai referensinya bisa dilihat disini : http://stackoverflow.com/questio...