如何在特定索引范围内对数组值求和

时间:2018-03-09 01:44:57

标签: javascript

如何使用像mod这样的索引值进行求和,这样的数组

var arr = [
    "Player ", "1", "Player ", "2", "Player ", "3", "Position", "In/Our", 
    "Position", "In/Our", "Position", "In/Our", "2", "1", "11", "0", "10", 
    "0", "6", "0", "10", "1", "5", "1", "8", "1", "11", "1", "11", "0", "3"];

我想计算关于指数的所有可除以6的值。

2 个答案:

答案 0 :(得分:1)

使用reduce

arr.reduce((acc, ele) => parseInt(ele) % 6 == 0 ? acc + parseInt(ele) : acc, 0)

答案 1 :(得分:1)

var words = ["Player ", "1", "Player ", "2", "Player ", "3", "Position", "In/Our", "Position", "In/Our", "Position", "In/Our", "2", "1", "11", "0", "10", "0", "6", "0", "10", "1", "5", "1", "8", "1", "11", "1", "11", "0", "3"];
var index=0;
var results = words.filter(word => {index= words.indexOf(word,index)+1;return ((index-1) % 6) == 0;});
console.log(results);

然后你可以用结果数组做任何你想做的事情,结果数组只包含6个可分割的索引元素