如何在javascript中使用for循环语句中的变量?
所以我试图让这个掷骰子数量等于指定的输入。为了达到这个目的,我使用了for循环,但是它不起作用。当我刚刚开始编码时,我不知道为什么。有人可以帮忙吗?如何在javascript中使用for循环语句中的变量?
<!DOCTYPE html>
<html>
<body>
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;
function FirstFunction() {
for (i=0; i<"a"; i++) {
x = Math.floor(Math.random() * 4) + 1;
random.push(x);
document.getElementById("display").innerHTML = random;
}
}
</script>
</body>
</html>
这不是你如何定义"a"
。
这是你如何做到这一点:
for (i=0; i<a; i++) {
这就是你如何从文本字段中的值:
var b = document.getElementById('textbox_id').value;
然后得到的整数值:
var a = parseInt(b);
然后for循环:
for (i=0; i<a; i++) {
这似乎也没有工作。 –
好的,这在某种程度上确实有效。然而,它应该给出一串等于a的数字,但是只有给出一个数字作为输出,不管我给出什么输入。 –
下面是你如何做到这一点。还有在评论中强调了几个问题:
function FirstFunction() {
// Reset array within this function
var random = [];
// Get value property, and convert to number (with +)
// And use var!
var a = +document.getElementById("diceamount").value;
// No quotes around a, and use var!
for (var i=0; i<a; i++) {
// Use var!
var x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// Only show after the loop, and use textContent
document.getElementById("display").textContent = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
注意,数组被隐式格式为逗号分隔值字符串时,你显示它。
谢谢。这正如我所想的那样工作。 –
马克他的回答接受了! –
看来你做错了,...
假设你想利用具有ID =“diceamount” 所以,输入的值,你必须存储在变量输入的值。
var a = document.getElementById('diceamount').value;
for(i = ; i<= a; i++){
your code
}
提出这个问题;并寻找一些教程的JavaScript
谢谢你的建议。非常感谢。 –
var random = [];
// not useful? but in your code
document.getElementById("display").innerHTML = random;
function FirstFunction(event) {
// get local value into a and use it the + avoids parseInt
let a = Math.abs(+document.getElementById("diceamount").value);
for (i=0; i<a; i++) {
// x was not declared and should be
let x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// could be textContent instead...outside loop
document.getElementById("display").innerHTML = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display">x</p>
注意,在函数外部使用'random'意味着它会一直追加值,不确定你是否期望这样做。 –
为'a'输入的负值 - 使用'Math.abs'使其成为正数不确定这是一个要求 –
什么是'I' “一”'是什么意思?你期望for循环执行多少次? – JCOC611
输入字段没有innerHTML。 – JJJ
Chrome开发人员工具(F12)中的控制台将帮助您了解可用的属性。例如,输入'document.getElementById(“diceamount”)'会给你一个对象,你会看到哪个属性保存你正在查找的值。 –