[英]JavaScript- get sum of values inside a for loop
I'm trying to sum all the variables, as many times as they appear in the loop, that is- for example if hitpoints appears 3 times(as in my code) sum -12 + -12 + -12; 我正在尝试对所有变量求和,就像它们在循环中出现的次数一样,例如-如果命中点出现3次(如我的代码所示),则总和为-12 + -12 + -12; And then at the end I need a final result - a sum of all of the variable values as many times as they appear.
然后最后,我需要一个最终结果-所有变量值的总和与它们出现的次数相同。
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);
I assume you want the sum of the points. 我假设您想要积分的总和。 Declare a variable sum and keep incrementing
声明一个变量和并保持递增
function calculate(number) { var hitpoints = -12; var points1 = 1; var points3 = 5; var points5 = 10; var pointsx = 15; var sum=0; for (var i =1; i <= number; i++) { if ( i%10 ===0) { sum += hitpoints; } else if ((i % 3 === 0) && (i% 5 ===0)) { sum += pointsx; } else if (i %3 ===0) { sum += points3; } else if(i%5 ===0) { sum += points5; } else { sum += points1; } } console.log(sum) } calculate(30);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.