![](/img/trans.png)
[英]My slider only shows 1st and 3rd slider but not the 2nd and 4th slider for table
[英]Given an array of numbers, return an array of numbers which contains 1st number, Sum of next 2 numbers (2nd, 3rd), Sum of next 3 numbers(4th,5th,6th)
给定一个数字数组,返回一个数字数组,其中包含第一个数字,接下来 2 个数字的总和(2nd, 3rd),接下来 3 个数字的总和(4th,5th,6th)
let num = [1, 5, 7, 2, 4, 9];
let result = [];
function sumOfIntegers(num) {
result.push(num[0]);
for(let i=1; i<num.length; i=i+3){
let prevNum1 = num [i]
let prevNum2 = num [i+1]
result.push(prevNum1 + prevNum2);
}
//console.log(result);
return result[];
}
sumOfIntegers(num);
这是我在js中完成的方式:
let num = [1, 5, 7, 2, 4, 9];
function sumOfIntegers(num) {
let result = [];
for(i=0; i<num.length; i++){
sum = 0
for(j=0; j<=i; j++){
sum += num[j]
}
result.push(sum)
}
return result;
}
console.log(sumOfIntegers(num));
我想到的方式是,您希望将列表中的所有整数从第一个点(索引 0)累积到您当前所在的点,再次遍历整个列表。 因此有两个嵌套的 for 循环。 神奇之处在于动态方法,因为无论您的 num-array 填充多少数字,这都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.