gpt4 book ai didi

javascript - 将返回值显示为文本

转载 作者:行者123 更新时间:2023-12-02 18:03:30 24 4
gpt4 key购买 nike

我有一些函数和一些变量。我想在浏览器上以文本形式返回一个变量和函数结果。

我所做的是制作了一个 HTML 文件,其中包含以下文本:

<SCRIPT SRC="rockpaper.js">
</SCRIPT>

这指的是这个 javascript 文件:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "Computer chooses rock";
} else if(computerChoice <= 0.67) {
computerChoice = "Computer chooses paper";
} else {
computerChoice = "Computer chooses scissors";
}

console.log(computerChoice);

var compare = function(choice1,choice2)
{
if(choice1===choice2)
{
return("The result is a tie!");
}

if(choice1==="Computer chooses rock")
{
if(choice2==="scissors")
{
return("rock wins");
}
else
{
return("paper wins");
}
}
if(choice1==="Computer chooses paper")
{
if(choice2==="rock")
return("paper wins");
else
{
return("scissors wins");
}
}
if(choice1==="Computer chooses scissors")
{
if(choice2==="rock")
{
return("rock wins");
}
else
{
return("scissors wins");
}
}
}

console.log(compare(computerChoice,userChoice))

但是,当我用浏览器打开它时,不显示文本,但显示提示。

不过,它在 Codecademy 中运行良好。

最佳答案

这是一个jsFiddle将数据记录到屏幕上。我注意到你的领带逻辑有缺陷。您正在将一个大字符串检查为用户简单的单字字符串。你需要标记化;从计算机选择字符串中提取状态。

Javascript

// Helpful utility function...
function logResultToScreen(result) {
var block = document.createElement('div');
var text = document.createTextNode(result);
var output = document.getElementById('output');

block.appendChild(text);
output.insertBefore(block);
}


var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

if (computerChoice < 0.34) {
computerChoice = "Computer chooses rock";
} else if (computerChoice <= 0.67) {
computerChoice = "Computer chooses paper";
} else {
computerChoice = "Computer chooses scissors";
}

console.log(computerChoice);
logResultToScreen(computerChoice);

var compare = function (choice1, choice2) {
var tokens = choice1.split(' ');

if (tokens[2] === choice2) {
return ("The result is a tie!");
}

if (choice1 === "Computer chooses rock") {
if (choice2 === "scissors") {
return ("rock wins");
} else {
return ("paper wins");
}
}
if (choice1 === "Computer chooses paper") {
if (choice2 === "rock") {
return ("paper wins");
} else {
return ("scissors wins");
}
}
if (choice1 === "Computer chooses scissors") {
if (choice2 === "paper") {
return ("scissors wins");
} else {
return ("rock wins");
}
}
}

var output = compare(computerChoice, userChoice);
logResultToScreen(output);
console.log(output);

HTML

<div id="output"><strong>Results:</strong></div>

关于javascript - 将返回值显示为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20310027/

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