var response = [];
response[0] = "Without a doubt";
response[1] = "Ask again later";
response[2] = "Don't count on it";
response[3] = "Signs point to yes";
response[4] = "Outlook not so good";
response[5] = "Better not tell you now";
var responseText = response[Math.floor(Math.random() * response.length)];
我有随机化变量的代码,但我不知道如何显示 responseText 的结果
控制台日志不起作用。
有很多方法可以做到这一点。
一个简单的方法是使用 alert
鉴于您的代码,这看起来像这样:
var response = [];
response[0] = "Without a doubt";
response[1] = "Ask again later";
response[2] = "Don't count on it";
response[3] = "Signs point to yes";
response[4] = "Outlook not so good";
response[5] = "Better not tell you now";
alert(response[Math.floor(Math.random() * response.length)])
另一种方法是将其记录到控制台。 为此,您可以将
alert
替换为 console.log
。
您也可以使用 document.write
,它也可以替换 alert
.
但通常你会操作 DOM 或 DOM 元素。这有点复杂,取决于你下一步打算做什么。
console.log 似乎工作正常
你的文件有问题吗?
var response = [];
response[0] = "Without a doubt";
response[1] = "Ask again later";
response[2] = "Don't count on it";
response[3] = "Signs point to yes";
response[4] = "Outlook not so good";
response[5] = "Better not tell you now";
var responseText = response[Math.floor(Math.random() * response.length)];
console.log(responseText);
如果你想在网页上显示结果,使用HTML:
var response = [];
response[0] = "Without a doubt";
response[1] = "Ask again later";
response[2] = "Don't count on it";
response[3] = "Signs point to yes";
response[4] = "Outlook not so good";
response[5] = "Better not tell you now";
var responseText = response[Math.floor(Math.random() * response.length)];
var resultHTML = document.getElementById("result");
resultHTML.textContent = responseText;
<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
</head>
<body>
<h1>Run the code to simulate a Magic 8-Ball:</h1>
<p>Result:</p>
<p id = "result"></p>
</body>
</html>
您可以使用 console.log() 将结果输出到浏览器控制台 和 document.writh() 将结果直接写入网页
console.log(responseText); document.write(responseText);