今天有人问我,如何创建一个由N个连续元素组成的数组,如[1,2,3,...,N]
(应从1开始),其中N
由用户提供。例如,如果N = 10,则数组将为[1,2,3,4,5,6,7,8,9,10]
。另外,他想对元素求和,所以如果N = 10,则结果为55。
我这样做如下:
console.log(new Array(10).fill(1).map((x,y)=>x+y).reduce((x,y)=>x+y))
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row{background: #000;color: #fff;}
.as-console-row-code{font-size:24px!important}
我只想问问解决相同问题的最佳方法是什么?为什么?
答案 0 :(得分:2)
答案 1 :(得分:2)
如果您仍然在考虑执行时间的情况下寻找“ best”解决方案,那么以下解决方案比Nina(https://jsfiddle.net/vc1wmk6e/)发布的解决方案快55倍:
function range (first, last) {
var range = new Array(last - first + 1); range[0] = first;
for (var i = 1; range[i - 1] < last; i++) range[i] = first + i;
return range;
}
console.log(...range(1, 10));
console.log(range(1, 10).reduce((acc, x) => acc + x));
要知道为什么它比fill
+ map
快(大约4.5倍),我们需要查看这两个函数的实现以计算它们的时间复杂度。我现在还不准备进入JS源代码,但是fill
和map
都有可能遍历数组元素。在这种情况下,时间复杂度至少为O(2N),而range
函数为O(N)。剩余的额外时间可能来自需要在内存中查找以找到相应代码的函数调用,但这纯粹是一种假设:-|
答案 2 :(得分:1)
您可以在进行汇总时删除地图,也可以通过简化操作来删除地图
console.log(new Array(10).fill(1).reduce((x,y,i) => x+y+i , 0))
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row{background: #000;color: #fff;}
.as-console-row-code{font-size:24px!important}