如何向对象添加提示条目并让它在另一个提示中回调?

How do I add prompt entry to object and have it called back in another prompt?

我正在制作一款猜色游戏。我正在尝试让提示询问玩家姓名,然后在游戏开始前的下一个提示中弹出玩家的名字和姓氏。

function user() {
    let player = {
        firstName: '',
        lastName: ''
    }

    player = prompt("To play enter your first and last name:");
    if (player === null) {
        alert("This game is cancelled.");
        return;
    } else {
        player.name = prompt("Thank you, let get started " + player.name + "!");
        runGame();
    }
}

您似乎混淆了变量名。您正在将名称的结果分配给 player 变量,而不是 player.name.

function user() {
    let player = {
      // if we're reading the full name at once we should get rid of redundancy
      name: null
    }

    // here we assign the result of the prompt to name attribute of player object
    player.name = prompt("To play enter your first and last name:");
    // honestly I don't know what empty prompt returns so I would fall back to rejecting all falsey values
    if (!player.name) {
        alert("This game is cancelled.");
        return;
    } else {
        // Alert is definitely a better choice here as the player doesn't input any information
        alert("Thank you, let get started " + player.name + "!");
        runGame();
    }
}

提示将return一个字符串,必须解析为用户的名字和姓氏。 split 可以做到。

最终提示将阻止用户输入。据推测,这是玩家将采取的第一步。我建议将第一个输入移至 runGame() 函数,将获取玩家名称和玩游戏的问题分开。

// just get a player object. (don't start the game)
function getUser() {
  let string = prompt("To play enter your first and last name:");
  if (!string) {
    alert("This game is cancelled.");
    return;
  }

  let names = string.split(' ');
  if (names.length < 2) {
    // handle a single name
  }

  let player = { firstName: names[0], lastName: names[1] };
  return player;
}

// start the game, given a player
function runGame(player) {
  let firstMove = prompt("Thank you, let get started " + player.firstName + "!");
  // run the game
}

let player = getUser();
if (player) runGame(player);