获取所有值的数组总和中的第n个值

时间:2014-11-07 15:27:38

标签: javascript for-loop

我有一个元素数组,我需要使用java脚本添加每个第一,七,十三和十九(70,74,50,70)个值和它们的总和。

var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];

任何人都可以提供帮助?谢谢!

4 个答案:

答案 0 :(得分:2)

我从你的问题中假设你必须在阵列发生变化时添加它们,在这种情况下你可以使用:

function sumIfDifferent( inputArr ) {
    var lastNum = -1;
    var total = 0;
    for (var i = 0, l = inputArr.length; i < l; i++) {
        num = parseInt(inputArr[i], 10);
        if (num != lastNum) {
            lastNum = num;
            total+=num;
        }
    }
    return total;
}

alert(sumIfDifferent(['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70']));

答案 1 :(得分:1)

只需添加它们:

&#13;
&#13;
var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];
document.write(parseInt(rowSpanHeight[0]) + parseInt(rowSpanHeight[6]) + parseInt(rowSpanHeight[12]) + parseInt(rowSpanHeight[18]));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

一个简单的方法是 -

  var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];
    var sum = ~~rowSpanHeight [0] + ~~rowSpanHeight [6] + ~~rowSpanHeight [12] + ~~rowSpanHeight [18];
    console.log(sum);

注意:这里使用~~(双波浪形)是一种将字符串转换为数字的快速方法,如果字符串为12.12则不会被用作~~将删除所有内容小数位后(很像parseInt)。有关https://stackoverflow.com/a/10841248/2737978

等SO问题的更多信息

答案 3 :(得分:0)

这样的事可能有用......

var sum=0;
for(var a in rowSpanHeight){
    switch(a){
        case 0:
        case 6:
        case 12:
        case 18:
             sum+=parseInt(rowSpanHeight[a]);
        break;
    }
}