我有一个元素数组,我需要使用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'];
任何人都可以提供帮助?谢谢!
答案 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)
只需添加它们:
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;
答案 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
答案 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;
}
}