我正在尝试制作一个简单的生成器,它从用户那里获取一些音节,并从中随机形成一个组成词。
我已经设法制作了一个不错的输入系统。它将音节放入一个二维数组。我已经对其进行了测试,并且可以正常工作。
当我尝试警告数组的随机部分时,它对我大喊:“未捕获的类型错误:无法读取未定义的属性 '0'”
<html>
<head>
<script type = "text/javascript">
var sounds = [[],[],[]];
function makeName(x){
alert(x[0][random(x[0].length)] + x[1][random(x[1].length)] + x[2][random(x[2].length)]); //Something is wrong here
}
function random(x){ //Random number between 0 and x-1
return Math.floor(Math.random()*x); //The problem might be here too
}
var Count0 = 0;
var Count1 = 0;
var Count2 = 0;
function add(type, fooNum) {
//Create an input type
var element = document.createElement("input");
//Add to index of user supplied data
if(fooNum == 1){
Count0++;
element.setAttribute("id","0:" + Count0);
}else if(fooNum == 2){
Count1++;
element.setAttribute("id","1:" + Count1);
}else if(fooNum == 3){
Count2++;
element.setAttribute("id","2:" + Count2);
}else{
alert("Somethin' went wrong, man!");
}
console.log(element.id);
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", "");
var foo = document.getElementById("fooBar"+fooNum);
//Append the element in page (in <span>).
foo.appendChild(element);
}
function generate(){ //Assign the inputs to a 2D array
var counts = [Count0, Count1, Count2];
hello=counts;
for(k=0; k<=2; k++){
for(i=0; i<=counts[k]; i++){
sounds[k][i] = document.getElementById(k + ":" + i).value;
alert(sounds[k][i]);
}
i = 0;
}
}
</script>
</head>
<body>
<FORM>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 1)"/><INPUT type="text" name="element" id="0:0"/><span id="fooBar1"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 2)"/><INPUT type="text" name="element" id="1:0"/><span id="fooBar2"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 3)"/><INPUT type="text" name="element" id="2:0"/><span id="fooBar3"> </span><P>
<INPUT type="button" value="Generate" onclick="generate()"/><P>
<INPUT type="button" value="Make Name" onclick="makeName()"/><P>
</FORM>
</body>
我的猜测是问题出在 random() 或 makeName() 中。
请帮忙!先感谢您。