我正在写一个类似风险的骰子游戏。 这不是整个代码,只是要求玩家姓名的功能。
function getPlayerNames(p1, p2, p3, p4){
p1 = prompt("What is Player 1's name?", '');p1;
p2 = prompt("What is Player 2's name?", '');p2;
p3 = prompt("What is Player 3's name?", '');p3;
p4 = prompt("What is Player 4's name?", '');p4;
return;
}
let player1Name, player2Name, player3Name, player4Name;
getPlayerNames(player1Name, player2Name, player3Name, player4Name);
当播放器(1,2,3,4)名称稍后在代码中使用时显示为“未定义”。有什么错误,它没有声明名称,因为它们在提示符中输入,并显示它们未定义?
答案 0 :(得分:1)
如评论中所述:JS does not pass by reference, it pass by value
说,这是一个可能的解决方案:
1.在函数内部输入名称
2.返回带有名称的数组
3.将名称分配给变量。
建议:另请阅读Variable Scopes
function getPlayerNames(){
let p1 = prompt("What is Player 1's name?", '');
let p2 = prompt("What is Player 2's name?", '');
let p3 = prompt("What is Player 3's name?", '');
let p4 = prompt("What is Player 4's name?", '');
return [p1,p2,p3,p4];
}
var names = getPlayerNames();
let player1 = names[0],
player2 = names[1],
player3 = names[2],
player4 = names[3];
console.log("Player 1: " + player1);
console.log("Player 2: " + player2);
console.log("Player 3: " + player3);
console.log("Player 4: " + player4);