如何在JavaScript中以随机方式随机播放数组?
_.shuffle()
_.shuffle 是属于 underscore.js的函数,underscore.js是javascript的框架。此函数实际上采用Fisher-Yates随机播放算法以随机方式随机播放元素。
语法
_.shuffle(array);
此方法将数组作为参数,并对其进行随机组合以随机获取元素。它使用Fisher-Yates混洗算法对数组进行混洗。对于单个输入,它会产生各种随机输出。
示例
<html> <body> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script> </head> <body> <script> document.write(_.shuffle(["raj", "pankaj", "rahim", "rachel", "Balakrishna"])) </script> </body> </html>
输出结果
rahim,Balakrishna,pankaj,raj,rachel
它还可以使用Fisher-Yates混合 算法来混合大型对象。对于单个输入,它给出各种输出。
示例
<html> <body> <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script> </head> <body> <script> var people = [ {"name": "Ram", "age": 27}, {"name": "Rahim", "age": 28}, {"name": "Rakul", "age": 29}, {"name": "Rohti", "age": 21} ] document.write(JSON.stringify(_.shuffle(people, 'age'))); </script> </body> </html>
输出结果
[{"name":"Rahim","age":28},{"name":"Rakul","age":29},{"name":"Ram","age":27},{"name":"Rohti","age":21}]