从Javascript中的数组中删除一个元素

Remove an element from an array in Javascript

本文关键字:一个 元素 删除 Javascript 数组      更新时间:2023-09-26

可能重复:
如何在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>")
    }
}

这是我的代码,但它输出相同的问题(字符串(,有时当我希望这三个问题是unqique时,我如何在输出后从数组中删除元素?

您需要使用数组的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);
    }
}

您可以尝试:

question.splice(rnd,1)

把它放在循环的末尾,它将删除刚刚显示的元素。

您可以跟踪已经使用的随机索引并避免它们,而不是从数组中删除元素。类似这样的东西:

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>")
  }
}

我同意Tim的回应。此外,您还可以通过这样做来压缩代码:

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不仅删除了元素,还返回了被删除的子数组。