首页 > 解决方案 > 随机团队生成器

问题描述

我有一个从一个数组中随机选择一个项目的按钮,以及一个从不同数组中随机选择的按钮。

我想要第三个按钮,它会从前两个数组的返回中随机选择。

这是我所拥有的:

//array 1
document.getElementById("east").addEventListener("click", getEast);

function getEast() {
    var x = [
        '1',
        '2',
    ];

    var rand = x[Math.floor(Math.random() * x.length)];

    document.getElementById("east").innerHTML = rand;

}

//array 2
document.getElementById("west").addEventListener("click", getWest);

function getWest() {
    var y = [
        '3',
        '4',
    ];

    var rand = y[Math.floor(Math.random() * y.length)];

    document.getElementById("west").innerHTML = rand;
}

document.getElementById("champ").addEventListener("click", getChamp);

// select champ from the two conference winners
function getChamp() {
    var z = [
        "function myEast();",
        "function myWest();"
    ];

    var rand = z[Math.floor(Math.random() * z.length)];

    document.getElementById("champ").innerHTML = rand;
}

标签: javascriptarrays

解决方案


您可以将代码更改为此

function getEast() {
    var x = [
        '1',
        '2',
    ];

    var rand = x[Math.floor(Math.random() * x.length)];

    document.getElementById("east").innerHTML = rand;

    return rand;
}

function getWest() {
    var y = [
        '3',
        '4',
    ];

    var rand = y[Math.floor(Math.random() * y.length)];

    document.getElementById("west").innerHTML = rand;

    return rand;
}


// select champ from the two conference winners
function getChamp() {
    var z = [
        getEast, getWest
    ];

    var rand = z[Math.floor(Math.random() * z.length)]();

    document.getElementById("champ").innerHTML = rand;
}

document.getElementById("east").addEventListener("click", getEast);
document.getElementById("west").addEventListener("click", getWest);
document.getElementById("champ").addEventListener("click", getChamp);

推荐阅读