简体   繁体   English

对特定索引范围内的数组元素求和

[英]Summing Array Elements from Specific Index Range

I have tried to look at many things for this but I simply cannot figure out how to make it work.我试图为此研究很多东西,但我根本无法弄清楚如何让它发挥作用。 I am very new to coding in general, so it may be a lack of understanding, Simply put, I have a an array with a set amount of elements, and I want to be able to sum up consecutive elements.一般来说,我对编码很陌生,所以可能缺乏理解,简单地说,我有一个包含一定数量元素的数组,我希望能够总结连续的元素。 starting from a specific index and ending at specific index.从特定索引开始,到特定索引结束。

const array = [1,2,3,4,5,6]

I want to be able to sum index 1 and 3, which in this case would be 2+4 =6.我希望能够将索引 1 和 3 相加,在本例中为 2+4 =6。

Is there a way to use array.filter() or just use a function where I sum based on the array.indexof() ?有没有办法使用array.filter()或只使用 function 我根据array.indexof()求和?

If you want to sum all the elements between two indexes, you can use a simple index based for loop.如果要对两个索引之间的所有元素求和,可以使用基于简单索引的 for 循环。

let start = 1, end = 3, sum = 0;
for(let i = start; i <= end; i++)
     sum += array[i];

slice and reduce can also be used:也可以使用slicereduce

let sum = array.slice(start, end+1).reduce((a,b)=>a+b,0);

If you just want the sum of the elements at two specific indexes, you can access the elements using bracket notation.如果您只想要两个特定索引处的元素之和,则可以使用括号表示法访问这些元素。

let sum = array[1]+array[3];

If you have an array of indexes to sum, you can loop over each index like so:如果你有一个索引数组要求和,你可以像这样遍历每个索引:

let indexes = [1, 3], sum = 0;
for(let index of indexes){
    sum += array[index];
}

reduce can be used as well.也可以使用reduce

let indexes = [1, 3];
let sum = indexes.reduce((acc, cur)=>acc+array[cur],0);

Try尝试

 const array = [1,2,3,4,5,6]; var startInd=1; var endInd=3; console.log(array[startInd]+array[endInd]);

You could use slice to take a chunk of the array and then use reduce您可以使用slice来获取数组的一部分,然后使用reduce

 const array = [1,2,3,4,5,6] subar = array.slice(1,4) res = subar.reduce((acc, curr, i) => acc = acc + curr,0) console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM