你可以使用Lodash _.shuffle,就像这样:
Template.userList.helpers({
users: function() {
return _.shuffle(Meteor.users.find().fetch());
}
});
随着热闹的作为似乎有是引擎盖下的区别:
下划线(source)
_.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)
_.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;
}
你可以看看this SO discussion进行了较深入了解比较这两个库。
Underscore和Lo-Dash都使用Fisher-Yates shuffle,你会比“更好”做的更困难。
问题:既然你在你的模板中使用了一个数组而不是一个光标,它仍然是被动的? – 2014-11-21 14:10:04
@Kyll,是的,但是如果对集合进行更新,整个帮助程序将被重新计算,所以没有很好的细化更新,这可能会也可能不是问题。 – 2014-11-21 15:08:54
这是我找到的最佳解决方案,我认为没有更好的方法来实现相同。 – SsouLlesS 2015-07-22 21:15:48