最近在复习数据结构与算法,特别是排序算法时,遇到一个有趣的问题:如何生成长度为n的随机数组来测试排序算法?看似简单,但使用new Array(n)却引发了意想不到的结果。
通常我们会这样生成随机数组:
function randomarray(n) { const arrtoreturn = []; for (let i = 0; i < n; i++) { arrtoreturn.push(Math.floor(Math.random() * 10)); } return arrtoreturn; }
这段代码完美运行。但我尝试寻找更简洁的单行代码,于是想到了new Array():
const randomarray = (n) => new Array(n).map(() => Math.floor(Math.random() * 10)); console.log(randomarray(5));
预期结果是一个包含5个随机值的数组,但实际输出却是[],令人困惑!然而,console.log(randomarray(5).length)却输出了5。
立即学习“Java免费学习笔记(深入)”;
问题的关键在于JavaScript中的稀疏数组。
稀疏数组包含一个或多个空槽。例如:
new Array(2) // [] [1, , , 3] // [1, , 3]
new Array(n)创建了一个长度为n的数组,但其槽位未初始化,并非空值或undefined。
当在稀疏数组上调用迭代方法(如forEach、map、reduce、filter)时,空槽会被跳过。
回到randomarray函数:
const randomarray = (n) => new Array(n).map(() => Math.floor(Math.random() * 10));
new Array(n)创建了一个稀疏数组,map方法跳过了所有空槽,导致输出为空数组。
.length方法返回数组长度的原因是,它取最大索引加1。稀疏数组虽然有空槽,但索引依然存在,因此.length返回预期长度。
为了解决这个问题,需要先用值填充稀疏数组的空槽,可以使用.fill()方法:
const randomArray = (n) => new Array(n).fill().map(() => Math.floor(Math.random() * 10)); console.log(randomArray(5));
现在,函数就能正确生成随机数组了。
以上就是“漏洞”真相:理解 JavaScript 的稀疏数组和意外行为的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号