这是一个完美创建数学序列的代码。唯一不同的是,它只对序列中的每个数字进行四舍五入,并最终分别计算最后一个数字。
目前的输出是:[0, 6, 12, 18, 24]
现在的问题是,我想要一个好的方法来创建另一个函数,该函数求和数组中的第一项和第二项,并像这样修改现有项:
因此,首先,代码创建了以下代码:[0, 6, 12, 18, 24]
然后我想将0和6相加并得到:[6, 12, 18, 24]
然后6和12:[18, 20, 22]
然后:[38, 22]
和:[60]
注意:每次我想为sn(数组中所有数字的总和)定义不同的值
编辑:换句话说,在新功能中,我必须再次重新分配这些行:
let a1 = 0; // first item of the array
let sn = 60; // sum of all numbers in the array
let total_Slides = 5;
var n = total_Slides; // total array or sequence length
var last = (sn - (n/2 * a1)) * 2/n // equation to calculate the last number if we want the sum of whole sequence will be equel to sn
var d = (last - a1) / (n - 1)
代码如下:
let reducer = (accumulator, currentValue) => accumulator + currentValue;
let reducere = (accumulator, currentValue) => accumulator + currentValue;
let a1 = 0; // first item of the array
let sn = 60; // sum of all numbers in the array
let total_Slides = 5;
var n = total_Slides; // total array or sequence length
var last = (sn - (n/2 * a1)) * 2/n // equation to calculate the last number if we want the sum of whole sequence will be equel to sn
var d = (last - a1) / (n - 1)
var next = [];
var sum = 0;
for (let i = 1; i < total_Slides; i++){
sum += a1 + (d * ( i - 1));
var pusher = int_part(sum);
next.push(pusher);
sum -= pusher
}
let sumer = sn - (next.reduce(reducer));
next.push(sumer)
let sumerr = next.reduce(reducere);
console.log(sumerr)
console.log(next)
function int_part(y){
return Math.trunc(y);
}
function float_part(d){
let int_part = Math.trunc(d);
return Number((d-int_part).toFixed(2));
}
答案 0 :(得分:3)
您可以获取前两个元素,并将其添加到广告中,然后将此值作为新数组的第一项并连接索引2以后的所有项。
var array = [0, 6, 12, 18, 24];
while (array.length > 1) {
array = [array[0] + array[1]].concat(array.slice(2));
console.log(...array);
}
答案 1 :(得分:0)
您可以使用.splice()
替换数组中的当前元素。
const numbers = [0, 6, 12, 18, 24];
while (numbers.length >= 2) {
let [a, b] = numbers;
numbers.splice(0, 2, a + b);
}
console.log(numbers);