函数(函数名采用驼峰命名)
var divideByThree = function(number) {
var val = number / 3;
console.log(val);
};
divideByThree(12);
// 4
Math.random() 返回值介于[0,1),包括0小于1
编写一个剪刀石头布的游戏
- 提示框,让用户输入剪刀、石头、布
- 判断用户输入的内容是否正确,如不符合弹出警告框并再次输入
- 电脑随机生成剪刀、石头、布
- 比较用户和电脑的值,判定输赢
var userChoice = prompt("剪刀、石头、布,三选一");
while (userChoice !== "剪刀" && userChoice !== "石头" && userChoice !== "布") {
confirm("你的输入不正确,请重新选择");
userChoice = prompt("剪刀、石头、布,三选一");
}
console.log("选手的选择是:" + " " + userChoice);
var computerChoice = Math.random();
if (computerChoice < 0.33) {
computerChoice = "剪刀";
}
else if (computerChoice <=0.67) {
computerChoice = "石头";
} else {
computerChoice = "布";
}
console.log("电脑的选择是:" + " " + computerChoice);
var compare = function(choice1, choice2) {
if (choice1 === choice2) {
console.log("打成平手!");
}
else if (choice1 === "剪刀") {
if (choice2 === "石头") {
console.log("石头获胜");
}
else {
console.log("剪刀获胜");
}
}
else if (choice1 === "石头") {
if (choice2 === "剪刀") {
console.log("石头获胜");
}
else {
console.log("布获胜");
}
}
else if (choice1 === "布") {
if (choice2 === "剪刀") {
console.log("剪刀获胜");
}
else {
console.log("布获胜");
}
}
};
compare(userChoice, computerChoice);