如果要按随机数索引,则应创建一个二维数组。
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"));