可能重复:
How to remove first element of an array in javascript?
function write() {
for (var x = 1; x <= 3; x++) {
var question = new Array("If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6");
var l = question.length;
var rnd = Math.floor(l * Math.random());
document.write(question[rnd]);
document.write("<br>")
}
}
这是我的代码,但有时当我想要三个问题不对时,它会输出相同的问题(字符串),如何在输出后从数组中删除元素?
答案 0 :(得分:3)
您需要使用数组的splice()
方法。但是,您每次迭代都会创建一个新数组,因此您需要将该部分移出循环。
function write() {
var questions = [
"If you are goofy which is your leading foot",
"Riding switch is when you do what",
"On your toe side which way should you lean",
"question 4",
"question 5",
"question 6"
];
for (var x = 1; x <= 3; x++) {
var rnd = Math.floor(questions.length * Math.random());
document.write(questions[rnd] + "<br>");
questions.splice(rnd, 1);
}
}
答案 1 :(得分:1)
您可以尝试:
question.splice(rnd,1)
将它放在循环的末尾,它将删除刚刚显示的元素。
答案 2 :(得分:0)
您可以跟踪已经使用过的随机索引,而不是从数组中删除元素,而是避免使用它们。像这样:
function write() {
for (var x = 1; x <= 3; x++) {
var question = new Array(...);
var used={}, l=question.length, rnd;
do {
rnd = Math.floor(l * Math.random());
} while (rnd in used);
used[rnd] = true;
document.write(question[rnd]);
document.write("<br>")
}
}
答案 3 :(得分:0)
我同意蒂姆的回应。此外,您可以通过这样做来压缩代码:
function write() {
var question = ["If you are goofy which is your leading foot", "Riding switch is when you do what", "On your toe side which way should you lean", "question 4", "question 5", "question 6"];
for (var x = 1; x <= 3; x++) {
var rnd = Math.floor(question.length * Math.random());
document.write(question.splice(rnd, 1)[0] + "<br>");
}
}
上述代码也可以使用的原因是splice不仅删除了元素,还返回了被删除的子数组。