gpt4 book ai didi

javascript - 控制台日志输出整个函数而不是返回的内容

转载 作者:行者123 更新时间:2023-11-29 19:44:03 25 4
gpt4 key购买 nike

我刚刚开始学习 JavaScript,并决定利用我目前获得的有限知识制作一款石头剪刀布游戏。但是,我不明白为什么会输出

I chose function (userChoice)
{
if(userChoice==="Rock")
return "Paper";

if(userChoice==="Paper")
return "Scissors";

if(userChoice==="Scissors")
return "Rock";
}. I win noob.

而不只是“我选择了摇滚。我赢了菜鸟。”

这是我的代码:

var main = function()
{
var yesno = confirm("Would you like to play Rock-Paper-Scissors?");

if(yesno === false)
return "You're lame.";

var userChoice = prompt("Rock, Paper, or Scissors?");

var cheat = function(userChoice)
{
if(userChoice==="Rock")
return "Paper";

if(userChoice==="Paper")
return "Scissors";

if(userChoice==="Scissors")
return "Rock";
};

return "I chose " + cheat + ". I win noob.";
};

console.log(main());

我发现它可以通过将 cheat 函数移动到 main 函数的外部和上方并调整一些东西来工作,代码可以按预期工作。我只是想不通为什么一种方法有效而另一种方法无效。

最佳答案

您忘记了 ():

return "I chose " + cheat(userChoice) + ". I win noob.";

有了圆括号,JavaScript 将在字符串中插入函数,而不是调用它并插入结果。

关于javascript - 控制台日志输出整个函数而不是返回的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21167389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com