我有两个数组
var mp3 = ['sing.mp3','song.mp3','tune.mp3','jam.mp3',etc];
var ogg = ['sing.ogg','song.ogg','tune.ogg','jam.ogg',etc];
我需要打乱两个数组,以便它们以相同的方式出现,例如:
var mp3 = ['tune.mp3','song.mp3','jam.mp3','sing.mp3',etc];
var ogg = ['tune.ogg','song.ogg','jam.ogg','sing.ogg',etc];
在 stackoverflow 上有几篇文章以不同的方式打乱数组 -- this one is pretty great --但它们都没有演示如何以完全相同的方式对两个数组进行洗牌。
谢谢!
最佳答案
向 Fisher-Yates 添加一个额外的参数洗牌。 (假设你的数组长度相等)
var mp3 = ["sing.mp3", "song.mp3"];
var ogg = ["sing.ogg", "song.ogg"];
function shuffle(obj1, obj2) {
var index = obj1.length;
var rnd, tmp1, tmp2;
while (index) {
rnd = Math.floor(Math.random() * index);
index -= 1;
tmp1 = obj1[index];
tmp2 = obj2[index];
obj1[index] = obj1[rnd];
obj2[index] = obj2[rnd];
obj1[rnd] = tmp1;
obj2[rnd] = tmp2;
}
}
shuffle(mp3, ogg);
console.log(mp3, ogg);
更新:
如果您要支持更多数组(如评论中所建议的),那么您可以按如下方式修改 Fisher-Yates(并执行一些检查以确保参数属于数组并且它们的长度匹配) .
var isArray = Array.isArray || function(value) {
return {}.toString.call(value) !== "[object Array]"
};
var mp3 = ["sing.mp3", "song.mp3", "tune.mp3", "jam.mp3"];
var ogg = ["sing.ogg", "song.ogg", "tune.ogg", "jam.ogg"];
var acc = ["sing.acc", "song.acc", "tune.acc", "jam.acc"];
var flc = ["sing.flc", "song.flc", "tune.flc", "jam.flc"];
function shuffle() {
var arrLength = 0;
var argsLength = arguments.length;
var rnd, tmp;
for (var index = 0; index < argsLength; index += 1) {
if (!isArray(arguments[index])) {
throw new TypeError("Argument is not an array.");
}
if (index === 0) {
arrLength = arguments[0].length;
}
if (arrLength !== arguments[index].length) {
throw new RangeError("Array lengths do not match.");
}
}
while (arrLength) {
rnd = Math.floor(Math.random() * arrLength);
arrLength -= 1;
for (argsIndex = 0; argsIndex < argsLength; argsIndex += 1) {
tmp = arguments[argsIndex][arrLength];
arguments[argsIndex][arrLength] = arguments[argsIndex][rnd];
arguments[argsIndex][rnd] = tmp;
}
}
}
shuffle(mp3, ogg, acc, flc);
console.log(mp3, ogg, acc, flc);
关于javascript - 以相同的方式打乱多个javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18194745/