plnkr.co上没有错误,但div按钮仍无法正常工作。
1)我是否在正确的轨道上从两个数组中提取两个随机数,添加它们并在单击按钮时返回结果。 2)我在这里运行代码时看到了未定义的错误,但我不确定要解决什么问题。代码没有给plnkr.co带来任何错误。
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomNumber = Math.floor(Math.random()*(num1 + num2));
document.getElementById("roll").innerHTML = randomNumber[rollDice];
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="randomNumber()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>
答案 0 :(得分:0)
您的代码存在一些问题:
您需要实际调用rollDice()函数。
你不能找到这样的randomNumber,你需要两个随机索引来从你定义的两个数组中选择两个数字。您可以使用Math.random()
,例如下面的代码:
randomNumber[rollDice]
错误,因为randomNumber是一个数字而不是一个对象。
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomIndex1 = Math.floor(Math.random()*num1.length);
var randomIndex2 = Math.floor(Math.random()*num2.length);
var randomNumber = num1[randomIndex1] + num2[randomIndex2];
document.getElementById("roll").innerHTML = randomNumber;
}
&#13;
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
&#13;
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>
&#13;
答案 1 :(得分:0)
我看到了一些事情。我重构了我认为你想要达到的目标。
//button event will generate 2 random numbers and add them together
var num1 = [1, 2, 3, 4, 5, 6];
var num2 = [1, 2, 3, 4, 5, 6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice() {
//random # between 1 and 6
var dice1 = Math.floor((Math.random() * num1.length) + 1);
var dice2 = Math.floor((Math.random() * num2.length) + 1);
var randomNumber = dice1 + dice2;
document.getElementById("roll").innerHTML = randomNumber;
}
&#13;
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
&#13;
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>
&#13;