javascript没有内置times方法,但可通过array.from、fill+map或for循环等原生方式实现循环调用函数生成指定长度数组的效果;2. array.from({ length }, mapfn) 是最推荐的现代写法,语义清晰且简洁;3. new array(n).fill(null).map(fn) 需填充以避免稀疏数组问题,适合需map转换的场景;4. for循环在性能和复杂逻辑控制上更具优势;5. 可自行封装times函数以获得更优雅的api;6. js未内置times是因其设计哲学倾向基础构建块,鼓励灵活组合,而非预设高层抽象,这也促进了工具库的发展;7. array.from相比fill+map语义更明确,性能略优,且无需担心空槽问题,是更优选择。
在JavaScript中,并没有一个名为
times
Array.from
Array.prototype.map
Array.prototype.fill
for
要实现“循环调用函数生成指定长度数组”的效果,我们有几种实用的原生JavaScript策略:
1. 使用 Array.from()
function generateArrayWithFunction(length, generatorFn) { return Array.from({ length: length }, (_, index) => generatorFn(index)); } // 示例:生成一个包含5个随机数的数组 const randomNumbers = generateArrayWithFunction(5, () => Math.random()); console.log(randomNumbers); // 比如:[0.12345, 0.67890, 0.11223, 0.44556, 0.77889] // 示例:生成一个包含索引平方的数组 const squares = generateArrayWithFunction(4, (index) => index * index); console.log(squares); // 输出:[0, 1, 4, 9]
这种方式简洁明了,意图清晰,尤其适合需要基于索引或只是简单重复调用函数的情况。
2. 结合 Array.prototype.fill()
Array.prototype.map()
undefined
null
map
function generateArrayWithMap(length, generatorFn) { return new Array(length).fill(null).map((_, index) => generatorFn(index)); } // 示例:生成3个日期字符串 const dates = generateArrayWithMap(3, () => new Date().toLocaleTimeString()); console.log(dates); // 比如:["10:30:00 AM", "10:30:00 AM", "10:30:00 AM"] (时间可能相同,因为是同步执行) // 注意:如果generatorFn是异步的,或者需要区分每次调用的上下文,这种方法会很直接。
fill(null)
map
3. 经典的 for
for
function generateArrayWithForLoop(length, generatorFn) { const result = []; for (let i = 0; i < length; i++) { result.push(generatorFn(i)); } return result; } // 示例:生成一个包含斐波那契数列前N项的数组(简化版) const fibonacci = generateArrayWithForLoop(6, (index) => { if (index <= 1) return index; // 这里为了简单,没有实现完整的斐波那契,只是示意 return index * 10; // 假装是斐波那契 }); console.log(fibonacci); // 输出:[0, 10, 20, 30, 40, 50] (如果generatorFn是简单的索引乘10) // 实际斐波那契实现会复杂些,需要闭包或外部状态。
for
4. 模拟一个 times
times(n, fn)
function times(n, iterator) { const result = []; for (let i = 0; i < n; i++) { result.push(iterator(i)); } return result; } // 示例:生成10个递增的字符串 const items = times(10, (i) => `Item ${i + 1}`); console.log(items); // 输出:["Item 1", "Item 2", ..., "Item 10"]
这其实就是
for
选择哪种方法,往往取决于你的具体需求、代码风格偏好以及对性能的考量。
Array.from
times
为什么JavaScript不像Ruby或者某些工具库那样,直接提供一个
times(n, callback)
你想啊,
for
while
forEach
map
reduce
times
Array.from
new Array(n).fill().map()
times
这带来了什么呢?我觉得是更大的自由度和组合性。当你没有一个现成的
times
for
Array.from
另外,这也促进了像Lodash这样的实用工具库的繁荣。这些库往往会封装一些在原生JS中需要多步操作才能完成的常见模式,比如
_.times
times
Array.from
new Array().fill().map()
Array.from
new Array(length).fill(null).map()
从性能上看,对于大多数现代JavaScript引擎,它们的性能差异通常不会是决定性的瓶颈,尤其是在处理中等规模数组时。不过,
Array.from
fill
真正的区别更多体现在语义和使用场景上:
Array.from({ length: N }, mapFn)
{ length: N }
mapFn
以上就是js 如何用times调用函数生成指定长度数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号