我对javascript很新,所以这个问题可能很愚蠢。 所以基本上我要做的就是有一个带字母a-z的数组。生成1-10的随机数并保存在变量中,该变量确定函数将返回多少个字母。之后,变量被赋予另一个函数,该函数将从数组中选择随机元素并将它们返回给html。我很难解释对不起
一切正常,但它一次只给一个皮肤而不是基于变量“letternum”的金额
这是我到目前为止的地方
var letters = [
"a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z",
];
function letters() {
var letternum = Math.floor(Math.random() * 10) + 1;
var i;
for (i = 1; i < letternum; i++) {
var random = Math.floor(Math.random() * letters.length) + 1;
var randletter = letters[random];
document.getElelemtById('div').innerHTML = "Random letters picked:" + randletter;
}
}
我为标题道歉我找不到更好的标题
答案 0 :(得分:1)
您的代码中存在一些错误:
getElementById
。letters
。=
覆盖以前写过的信件。Math.random() * (letters.length - 1)
来避免获取undefined
(由于索引超出范围)。
var letters = [
"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z",
];
function lettersFunction() { // a different name
var letternum = Math.floor(Math.random() * 10) + 1;
var i;
for (i = 1; i < letternum; i++) {
var random = Math.floor(Math.random() * (letters.length - 1)) + 1;
var randletter = letters[random];
document.getElementById('div').innerHTML += "Random letter picked: " + randletter + '<br>'; // += instead of =, and add a new line after each letter
}
}
lettersFunction(); // calling the function
&#13;
<div id="div"></div>
&#13;
答案 1 :(得分:0)
document.getElelemtById('div').innerHTML = "Random letters picked:" + randletter;
循环结束时的这一行改变了innerHTML,所以你只剩下随机数中的最后一行。您可以将其更改为:
document.getElelemtById('div').innerHTML += "Random letters picked:" + randletter;
所以他们被附加。
答案 2 :(得分:0)
你的显示功能在你的for循环中 - 意味着它会为它选择的每个字母显示一次。你想要做的是在for循环中将字母连接在一起并显示一次:
var letters = [
"a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z",
];
function letters(){
var letternum = Math.floor(Math.random() * 10) + 1;
var i;
var randletter;
for (i = 1; i < letternum; i++) {
var random = Math.floor(Math.random() * letters.length) + 1;
randletter += letters[random];
}
document.getElelemtById('div').innerHTML = "Random letters picked:" + randletter;
}
答案 3 :(得分:0)
只需更新innerHTML,不要覆盖它。删除拼写错误并使用除div之外的div的其他ID。
document.getElementById('numdiv').innerHTML += "Random letters picked:" + randletter;
代码:
<div id="numdiv" onclick="randletters();">Click</div>
<script>
var letters = [
"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z",
];
function randletters() {
var letternum = Math.floor(Math.random() * 10) + 1;
var i;
for (i = 1; i < letternum; i++) {
var random = Math.floor(Math.random() * letters.length) + 1;
var randletter = letters[random];
document.getElementById('numdiv').innerHTML += "Random letters picked:" + randletter + "<br>";
}
document.getElementById('numdiv').innerHTML += "<br><hr>";
}
</script>