在下面的代码中,当我将userDoor变量设置为提示的用户输入时,用户输入附加到变量。我知道这一点,因为该值显示在变量声明正下方的console.log语句中。
然而,变量revealDoor和offerDoor是基于userInput变量设置的,它们表示变量没有“捕捉”#34;价值。 ( Wonky :比说明更容易演示。请运行下面的代码.UserDoor,revealDoor和offerDoor都应该是1-3范围内的不同数字。有些时候,revealDoor === userDoor。这绝不会发生。)。
有趣的是,当我将userDoor直接设置为整数时,程序运行正常 - 请参阅注释调试行。
为什么 userInput变量会在控制台中显示正确的值,但似乎没有捕获到程序的其余部分?
(顺便说一下,这个程序是为了说明monty hall paradox
alert("There are 3 doors. Behind two of them are DEATH and DOOM. Behind the other is a BIG TASTY SAUSAGE.");
var yWin = 0;
var yLoss = 0;
var nWin = 0;
var nLoss = 0;
while(true){ //noprotect
var userDoor = prompt("choose door: 1, 2, or 3");
//var userDoor = 1 //debug
console.log('UD: ' + userDoor);
var prizeDoor = randomRange(1,3);
console.log('PD: ' + prizeDoor);
var revealDoor = (function(){
var revealDoor = prizeDoor;
if (prizeDoor === userDoor) {
while (revealDoor === prizeDoor) {
revealDoor = randomRange(1,3);
}
return revealDoor;
}
else {
while (revealDoor === prizeDoor || revealDoor === userDoor){
revealDoor = randomRange(1,3);
}
return revealDoor;
}
})();
console.log('RD: ' + revealDoor);
var offerDoor = (function(){
var offerDoor = prizeDoor;
while(offerDoor === revealDoor || offerDoor === userDoor){
offerDoor = randomRange(1,3);
}
return offerDoor;
})();
console.log('OD: ' + offerDoor);
var choice = prompt("You chose door " + userDoor + ". Behind door " + revealDoor + ", I reveal DEATH AND DOOM. I would like to offer you the chance to change your choice to " + offerDoor + ". Do you accept--y/n?");
if(choice === "y"){
userDoor = offerDoor;
}
var result = (function(){
var result;
if(userDoor === prizeDoor){
alert("YOU FOUND THE PRIZE!");
result = 'w';
}
else {
alert("You chose DEATH AND DOOM!");
result = 'l';
}
return result;
})();
//Analytics:
switch(result){
case 'w':
if(choice === 'y'){
yWin++;
}
else {
nWin++;
}
break;
case 'l':
if(choice === 'y'){
yLoss++;
}
else {
nLoss++;
}
break;
}
var done = prompt("Are you Done? y/n");
if(done === "y"){
break;
}
}
function randomRange(min, max) {
return Math.floor(Math.random () * (max - min +1)) + 1;
}
var totalSamples = yWin + nWin + yLoss + nLoss;
var yChoices = yWin + yLoss;
var nChoices = nWin + nLoss;
console.log('With a sample set of ' + totalSamples);
console.log('You chose to change ' + (yChoices/nChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to change, you\'ve won ' + (yWin/yChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to stay, you\'ve won ' + (nWin/nChoices * 100) + '% of the time.');

答案 0 :(得分:1)
var userDoor = prompt("choose door: 1,2, or 3")) * 1
这个
更好用2个单选按钮答案 1 :(得分:0)
问题是prompt()返回一个字符串。这意味着任何' ==='比较返回undefined。我需要使用Number()
将返回的字符串转换为数字。
var userDoor = Number(prompt("choose door: 1,2, or 3"))
答案 2 :(得分:0)
使用
var done = confirm("Are you Done? y/n");
if (done) break;
而不是d提示确认