简体   繁体   English

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

[英]Get nth value in array sum of all values

I have an array of elements, i need to add the every first, seven, thirteen and nineteen (70, 74, 50, 70) values and sum of them using java script. 我有一个元素数组,我需要使用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'];

Anyone can help? 有人可以帮忙吗? Thanks! 谢谢!

I assume from your question that you have to add them whenever they change in the array, in that case you can use: 我从您的问题假设,只要它们在数组中更改,就必须添加它们,在这种情况下,您可以使用:

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']));

Simply add them up: 只需将它们加起来即可:

 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])); 

a simple approach would be - 一个简单的方法是-

  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); 

note: the use of ~~ (double tilde) here is a quick way to convert the string to a number, had the string been 12.12 this would not have been used as ~~ will remove everything after a decimal place (much like parseInt). 注意:这里使用~~ (双波浪号)是将字符串转换为数字的快速方法,如果字符串是12.12,则本不会使用该字符,因为~~将删除小数点后的所有内容(类似于parseInt) 。 more info in SO questions like https://stackoverflow.com/a/10841248/2737978 SO问题的更多信息,例如https://stackoverflow.com/a/10841248/2737978

something like this might work ... 这样的事情可能会起作用...

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

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

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