你可以使用洛达什_.shuffle https://lodash.com/docs#shuffle,像这样:
Template.userList.helpers({
users: function() {
return _.shuffle(Meteor.users.find().fetch());
}
});
尽管这看起来很搞笑,但is引擎盖下的差异:
下划线 (source https://github.com/jashkenas/underscore/blob/master/underscore.js)
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
Lo-Dash (为便于比较略有修改, source https://github.com/lodash/lodash/blob/master/lodash.js)
_.shuffle = function(collection) {
MAX_ARRAY_LENGTH = 4294967295;
return sampleSize(collection, MAX_ARRAY_LENGTH);
}
function sampleSize(collection, n) {
var index = -1,
result = toArray(collection),
length = result.length,
lastIndex = length - 1;
n = clamp(toInteger(n), 0, length);
while (++index < n) {
var rand = baseRandom(index, lastIndex),
value = result[rand];
result[rand] = result[index];
result[index] = value;
}
result.length = n;
return result;
}
你可以看一下这个SO讨论 https://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore更深入地了解这两个库的比较。
Underscore 和 Lo-Dash 都使用费舍尔-耶茨洗牌 https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle你很难做得“更好”。