javascript - 有人可以解释一下这个功能是如何工作的吗?
问题描述
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] =
o[j], o[j] = x);
return o;
};
不太确定最后一部分在做什么
解决方案
这看起来像是有人接受了“我可以在一条线上完成”的挑战,这是一个非常简洁有趣的挑战,但在现实世界的代码中没有位置——你的同事会讨厌你。所以让我们把它扩展成可读的东西:
function shuffle(o) {
// iterate over the entire input array "o"
for(var i = o.length - 1; i; i--) {
// get the "current" item and save it in variable "x"
var x = o[i];
// generate a random number within the bounds of the array
var j = parseInt(Math.random() * (i + 1));
// The next two lines essentially swap item[i] and item[j]
// set the "current" item to a randomly picked item
o[i] = o[j];
// put the "current" item in the random position
o[j] = x;
}
return o;
};
推荐阅读
- php - 使用 Select 表单过滤使用 PHP 从 MySQL 查询的表
- javascript - 在 Python 中读取导出的 Javascript 对象
- struts2 - 如何将变量传递给 s:text?
- node.js - 需要帮助建立 nodejs (NPM) localhost https
- uwp - 升级到 Win10 1803 后无法“dotnet restore”,失败并出现错误 MSB4019,即使在空白项目上也是如此
- javascript - 无法在模式中刺激 Input 的变化:React-Redux
- android - 将按钮更改为以编程方式舍入
- karate - 我也可以对 Json Api 请求使用以下相同的功能吗
- python - 如何在压缩和解压缩文件夹中搜索特定行
- c# - 是否可以将后代对象的集合作为 .NET Core 中的视图模型传入?