使用 AngularJS 如何随机化集合的顺序? [英] Using AngularJS how could I randomize the order of a collection?
问题描述
你会如何在 AngularJS 中以随机顺序排列项目列表?我在想内置的 orderBy
过滤器会起作用,但我不确定如果不向模型添加一些额外的数据.像这样的东西会很棒.
How would you order a list of items in AngularJS in random order? I was thinking that the built-in orderBy
filter would work but I'm not sure how without adding some additional data to the model. Something like would be great.
item in items | orderBy:random
我的下一个想法是创建一个自定义过滤器,但如果已经有更好的东西可用,我宁愿避免这种情况.
My next thought was to create a custom filter but I'd prefer to avoid that if there is something better already available.
推荐答案
编辑警告!:这些结果是有偏差的,不要使用它.此答案仅作为警告留待进一步编辑.
EDIT Warning!: These results are skewed, don't use this. This answer is only left as a warning until further editing.
解释:任何项目在第一个位置的概率应该是相等的,但是在 10,000 次迭代后的实际百分比,例如 6 个项目,最终是
Explanation: There should be an equal chance of any item being in the first position, but the actual percent chance after 10,000 iterations of, for example, 6 items, ends up being
1: ~28%, 2: ~10%, 3: ~14%, 4: ~20%, 5: ~12%, 6: ~15%
1: ~28%, 2: ~10%, 3: ~14%, 4: ~20%, 5: ~12%, 6: ~15%
https://jsfiddle.net/sh0ber/km9cqvpf/
orderBy
可以接受一个函数参数,就像 array.sort
这样你可以使用上面的 HTML 并在上面定义一个函数 random
范围如:
orderBy
can take a function parameter, just like array.sort
so you can use your HTML above and define a function random
on the scope like:
$scope.random = function(){
return 0.5 - Math.random();
};
这将返回一个随机值,有时为负,有时为正,有时为 0,这将对数组进行随机排序.
This will return a random value sometimes negative, sometimes positive, sometimes 0, which will randomly sort the array.
这篇关于使用 AngularJS 如何随机化集合的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!