Javascript:生成和存储随机抽取而无需替换

问题描述 投票:0回答:1

我正在尝试使用Javascript创建一个数组,从数组中获取两个独特的随机抽取,然后将绘制的值分配给HTML表。我的方法是创建一个数组,随机,创建一个没有绘制值的新数组,然后从新数组中随机抽取,作为一种无需替换的两次随机抽取的方法。

我提供了一个最简单的例子,说明我为实现这一目标所做的一切,但它没有用。我希望分配给HTML表的值最终是来自foo数组的两个唯一值(例如“a”,“b”)。这是不行的,因为下面的值== bar_a不会删除分配给bar_a数组的值,因为bar_a是一个数组而不是数组的值?

虽然this post已经解决了没有替换的绘图,但它没有提供使用字符串或解释如何保存这两个数字的例子,并且不清楚为什么他们使用splice()而不是filter()

    // Define array containing the set of values we'll randomly assign to A or B
    var foo = ["a", "b", "c", "d"];

    // Initialize variables to hold the value for A and B
    var bar_a=  [""];
    var bar_b=  [""];

    // Randomly draw from foo, save for A
    bar_a =foo[Math.floor(Math.random()*foo.length)];

    // Remove the drawn value from the array, create new array
    var foo_filtered = array.filter(function(value, index, arr){
        return value == bar_a;
        });

    // Randomly draw from foo_filtered, save for B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign attributes and values to their placeholders (a1, b1) in a HTML table
     document.getElementById("a1").innerHTML = bar_a;
     document.getElementById("b1").innerHTML = bar_b;
javascript arrays random replace qualtrics
1个回答
1
投票

您的过滤条件逻辑是向后的。你想要的价值不等于bar_a

您还需要将array.filter更改为foo.filter

    // Define array containing the set of values we'll randomly assign to A or B
    var foo = ["a", "b", "c", "d"];

    // Initialize variables to hold the value for A and B
    var bar_a=  [""];
    var bar_b=  [""];

    // Randomly draw from foo, save for A
    bar_a =foo[Math.floor(Math.random()*foo.length)];

    // Remove the drawn value from the array, create new array
    var foo_filtered = foo.filter(function(value, index, arr){
        return value !== bar_a;
                  // ^^ not equal
        });

    // Randomly draw from foo_filtered, save for B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign attributes and values to their placeholders (a1, b1) in a HTML table
     document.getElementById("a1").innerHTML = bar_a;
     document.getElementById("b1").innerHTML = bar_b;
A: <span id="a1"></span>   B: <span id="b1"></span>
© www.soinside.com 2019 - 2024. All rights reserved.