洗牌多个JavaScript数组以同样的方式 [英] Shuffle multiple javascript arrays in the same way
问题描述
我有两个数组
var mp3 = ['sing.mp3','song.mp3','tune.mp3','jam.mp3',etc];
var ogg = ['sing.ogg','song.ogg','tune.ogg','jam.ogg',etc];
我需要让他们走出同样的方式来洗牌两个数组,例如:
i need to shuffle both arrays so that they come out the same way, ex:
var mp3 = ['tune.mp3','song.mp3','jam.mp3','sing.mp3',etc];
var ogg = ['tune.ogg','song.ogg','jam.ogg','sing.ogg',etc];
有以不同的方式洗牌阵列计算器上的几个帖子 - 的这一次是pretty伟大 - 但他们没有说明如何洗牌两个数组以相同的确切方式。
there's a few posts on stackoverflow that shuffle arrays in different ways--this one is pretty great--but none of them demonstrate how to shuffle two arrays in the same exact way.
日Thnx!
推荐答案
添加一个额外的参数给的费雪耶茨洗牌。 (假设你的数组长度相等)
Add an extra argument to the Fisher-Yates shuffle. (assumes that your arrays are equal length)
的JavaScript
Javascript
var mp3 = ["sing.mp3", "song.mp3", "tune.mp3", "jam.mp3"],
ogg = ["sing.ogg", "song.ogg", "tune.ogg", "jam.ogg"];
function shuffle(obj1, obj2) {
var l = obj1.length,
i = 0,
rnd,
tmp1,
tmp2;
while (i < l) {
rnd = Math.floor(Math.random() * i);
tmp1 = obj1[i];
tmp2 = obj2[i];
obj1[i] = obj1[rnd];
obj2[i] = obj2[rnd];
obj1[rnd] = tmp1;
obj2[rnd] = tmp2;
i += 1;
}
}
shuffle(mp3, ogg);
console.log(mp3, ogg);
更新:
如果您要支持多个磁盘阵列(如在评论中所建议的),那么你可以修改费雪耶茨如下(藏汉作为进行一些检查,以确保该参数是阵列,它们的长度相匹配)
If you are going to support more arrays (as suggested in the comments), then you could modify the Fisher-Yates as follows (aswell as perform some checks to make sure that the arguments are of Array and that their lengths match).
的JavaScript
Javascript
var mp3 = ["sing.mp3", "song.mp3", "tune.mp3", "jam.mp3"],
ogg = ["sing.ogg", "song.ogg", "tune.ogg", "jam.ogg"],
acc = ["sing.acc", "song.acc", "tune.acc", "jam.acc"];
flc = ["sing.flc", "song.flc", "tune.flc", "jam.flc"];
function shuffle() {
var length0 = 0,
length = arguments.length,
i,
j,
rnd,
tmp;
for (i = 0; i < length; i += 1) {
if ({}.toString.call(arguments[i]) !== "[object Array]") {
throw new TypeError("Argument is not an array.");
}
if (i === 0) {
length0 = arguments[0].length;
}
if (length0 !== arguments[i].length) {
throw new RangeError("Array lengths do not match.");
}
}
for (i = 0; i < length0; i += 1) {
rnd = Math.floor(Math.random() * i);
for (j = 0; j < length; j += 1) {
tmp = arguments[j][i];
arguments[j][i] = arguments[j][rnd];
arguments[j][rnd] = tmp;
}
}
}
shuffle(mp3, ogg, acc, flc);
console.log(mp3, ogg, acc, flc);
这篇关于洗牌多个JavaScript数组以同样的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!