我想在带有for循环的数组中插入15个随机值。 这是我的代码,但它不起作用......
var cardArray[]; //set up empty array
for (var i = 0; i <= 15; i++) {
var NumberCard = Math.floor((Math.random() * 50) + 1);
var NameCard = Math.floor((Math.random() * 4) + 1);
cardArray[i] = "Number Card: " + NumberCard + " Name Card: "+ NameCard;
}
for (var i = 0; i <= 15; i+=2) {
document.writeln(cardArray[i] + "<br />");
}
答案 0 :(得分:0)
你没有很好地定义cardArray,它应该是=&gt; var cardArray = []
另外,为什么你在第二个循环中做i+=2
?你想跳过值吗?我将其更改为i++
var cardArray = []; //set up empty array
for (var i = 0; i <= 15; i++) {
var NumberCard = Math.floor((Math.random() * 50) + 1);
var NameCard = Math.floor((Math.random() * 4) + 1);
cardArray[i] = "Number Card: " + NumberCard + " Name Card: "+ NameCard;
}
for (var i = 0; i <= 15; i++) {
document.writeln(cardArray[i] + "<br />");
}
答案 1 :(得分:0)
因为你需要先定义数组,就像这样!
var cardArray = new Array(15); //set up empty array
for (var i = 0; i <= 15; i++) {
var NumberCard = Math.floor((Math.random() * 50) + 1);
var NameCard = Math.floor((Math.random() * 4) + 1);
cardArray[i] = "Number Card: " + NumberCard + " Name Card: "+ NameCard;
}
for (var i = 0; i <= 15; i+=2) {
document.writeln(cardArray[i] + "<br />");
}
答案 2 :(得分:0)
问题出在你的声明中。变化
var cardArray[];
到
var cardArray = [];
var cardArray = []; //set up empty array
for (var i = 0; i <= 15; i++) {
var NumberCard = Math.floor((Math.random() * 50) + 1);
var NameCard = Math.floor((Math.random() * 4) + 1);
cardArray[i] = "Number Card: " + NumberCard + " Name Card: "+ NameCard;
}
for (var i = 0; i <= 15; i+=2) {
document.writeln(cardArray[i] + "<br />");
}
答案 3 :(得分:0)
var cards = [];
function getRand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
for (var i = 0; i <= 15; i++) {
cards.push("Number Card: " + getRand(1, 50) + " Name Card: " + getRand(1, 4));
var div = document.createElement("div");
div.innerHTML = cards[i];
document.body.appendChild(div);
}
&#13;