这可能是一个奇怪的问题,因为我有一个解决方案(下面),但我希望有人能向我展示一种更简洁或更易读的方法来做到这一点:
我创建了一个循环,用于输出以下数组:
0、1、3、6、10、15、21、28、36、45、55、66、78、91
数字之间的差距越来越大:
1-0 = 1
3-1 = 2
6-3 = 3
10-6 = 4
...
91-78 = 13
等。
我创建了两个变量,step
跟踪间隙大小,count
跟踪缺口中当前的“位置”。count
计数为零,然后将step
增加1。
var output = [];
var step = 0;
var count = 0;
for (var i = 0; i < 100; i++) {
if (count == 0){
step += 1;
count = step;
output.push(i);
}
count -= 1;
}
发布于 2017-01-05 00:07:08
您可以尝试以下方法:
var output = [];
var total = 0;
for (var i=1; i < 100; i++) {
output.push(total);
total += i;
}
数字之间的差距在每一步中都会增加一个,所以for循环应该能够跟踪这个变化。
发布于 2017-01-05 00:10:51
您应该跳过无用的迭代。如果您想要100个数字的序列,请使用
var output = [];
var step = 0;
for (var i = 0; i < 100; i++) {
step += i;
output.push(step);
}
如果你想要通用术语,
aₙ = ∑ⁿᵢ₌₀ i = n*(n+1)/2
所以你也可以
var output = [];
for (var i = 0; i < 100; i++) {
output.push(i * (i+1) / 2);
}
发布于 2017-01-05 20:43:29
可以使用此解决方案保存总助手变量:
var output = [0]
for (var i = 1; i < 14; i++) {
output.push(output[i - 1] + i)
}
console.log(output) // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
此解决方案考虑到要添加计数器值的值已经存在于数组中的最后一个位置。
递归版本也是可能的:
output = (function f(x) {
return x.length == 14 ? x : f(x.concat([x[x.length - 1] + x.length]))
})([0])
console.log(output); // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
这里不需要额外的计数器变量。我使用concat
,因为它返回递归调用所需的数组,其中push
返回新的数组长度。concat
的参数是一个数组,其中有一个要添加新值的元素。
试试在线
https://stackoverflow.com/questions/41475254
复制相似问题