You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将函数调用结果传入playRound时值为undefined的问题求助

函数参数遮蔽导致变量undefined的问题解决

问题原因

你定义了全局的computerSelection和playerSelection变量,但在playRound函数的参数列表里又使用了同名变量,这触发了变量遮蔽:函数内部的参数会优先覆盖全局作用域的同名变量。而你没有调用playRound并传入参数,所以函数内部的这两个参数值就是undefined。

另外,你原代码里的胜负判断逻辑错误——用>和<比较字符串是基于ASCII码的,完全不符合石头剪刀布的胜负规则,必须修正。

解决方法

方法一:移除函数参数,直接使用全局变量

const computerSelection = getComputerChoice();
const playerSelection = getPlayerChoice();

let playRound = () => {
    const playerWin = `You win, you choose ${playerSelection} and the computer picked ${computerSelection}`;
    const computerWin = `You loose, you choose ${playerSelection} and the computer picked ${computerSelection}`;
    const draw = `Ohhhhhhh, a drawww , You choose ${playerSelection} and the computer picked ${computerSelection}`;

    if (playerSelection === computerSelection) {
        return draw; 
    } 
    // 正确的石头剪刀布胜负判断逻辑
    else if (
        (playerSelection === "rock" && computerSelection === "scissors") ||
        (playerSelection === "paper" && computerSelection === "rock") ||
        (playerSelection === "scissors" && computerSelection === "paper")
    ) {
        return playerWin; 
    } else {
        return computerWin; 
    }
}

// 调用函数
console.log(playRound());

方法二:保留函数参数,调用时传入全局变量

这种方式让函数更独立,复用性更强:

const computerSelection = getComputerChoice();
const playerSelection = getPlayerChoice();

let playRound = (playerSelection, computerSelection) => {
    const playerWin = `You win, you choose ${playerSelection} and the computer picked ${computerSelection}`;
    const computerWin = `You loose, you choose ${playerSelection} and the computer picked ${computerSelection}`;
    const draw = `Ohhhhhhh, a drawww , You choose ${playerSelection} and the computer picked ${computerSelection}`;

    if (playerSelection === computerSelection) {
        return draw; 
    } 
    // 正确的石头剪刀布胜负判断逻辑
    else if (
        (playerSelection === "rock" && computerSelection === "scissors") ||
        (playerSelection === "paper" && computerSelection === "rock") ||
        (playerSelection === "scissors" && computerSelection === "paper")
    ) {
        return playerWin; 
    } else {
        return computerWin; 
    }
}

// 调用时传入参数
console.log(playRound(playerSelection, computerSelection));

内容的提问来源于stack exchange,提问作者Sawmail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:20:16