0

我正在尝试在一个数组中随机化一组 3 个数组,然后使用从随机化中选择的 id 设置链接,这很难解释,但希望我的代码可以帮助您理解我正在尝试做的事情:

var options = { 
    option1: ["#boss", "#esprit", "#escada"],
    option2: [ "#esprit","#boss", "#escada"],
     option3: ["#escada",  "#esprit", "#boss" ]
};

var randomOption = options[Math.floor(Math.random() * 3 )];

    $("a.test1").attr("id", randomOption[0])
    $("a.test2").attr("id", randomOption[1])
    $("a.test3").attr("id", randomOption[2])

这段代码不起作用,有什么想法我需要做什么吗?

谢谢。

4

2 回答 2

1

如果要按随机数索引,则应创建一个二维数组。

var options = [
    ["#boss", "#esprit", "#escada"],
    ["#esprit", "#boss", "#escada"],
    ["#escada", "#esprit", "#boss"]
];

var randomOption = options[Math.floor(Math.random() * options.length)];

for (var i = 1; i <= options.length; i++)
    $("a.test" + i).attr("id", randomOption[i-1]);

for (var i = 1; i <= options.length; i++)
    console.log("Test " +i+ ": " + $("a.test" + i).attr("id"));

这是上面代码的 JSFiddle:http: //jsfiddle.net/XugvM/2

您还可以制作一个一维数组并像@RoryPickering 提到的那样洗牌:http: //jsfiddle.net/XugvM/8/

// Define a shuffle function for the Array class.
if (!Array.prototype.hasOwnProperty('shuffle')) {
    Array.prototype.shuffle = function(array) {
        var counter = this.length, temp, index;

        // While there are elements in the array.
        while (counter > 0) {
            // Pick a random index.
            index = Math.floor(Math.random() * counter);

            // Decrease counter by 1.
            counter--;

            // Swap the last element with it.
            temp = this[counter];
            this[counter] = this[index];
            this[index] = temp;
        }
    }
}

// Define variables.
var options = ["#boss", "#esprit", "#escada"];
var optionsLength = options.length;

// Shuffle options.
options.shuffle();

// Assign the ids for the anchors.
for (var i = 0; i < optionsLength; i++)
    $("a.test" + (i + 1)).attr("id", options[i]);

// Print each of the ids in the log console.
for (var i = 1; i <= optionsLength; i++)
    console.log("Test " +i+ ": " + $("a.test" + i).attr("id"));
于 2013-06-12T22:22:28.017 回答
0

看看这里:http: //jsfiddle.net/M6z6M/

代码

var options = {
    option1: ["#boss", "#esprit", "#escada"],
    option2: ["#esprit", "#boss", "#escada"],
    option3: ["#escada", "#esprit", "#boss"]
};
var rnd = Math.floor((Math.random() * 3) + 1);
var randomOption = options["option" + rnd];

$("a.test1").attr("id", randomOption[0])
$("a.test2").attr("id", randomOption[1])
$("a.test3").attr("id", randomOption[2])

单击每个链接以查看打印的该链接的 ID

于 2013-06-12T21:56:39.160 回答