好吧,所以我正在努力做一个小程序来做GPA(练习,帮助我学习更多的东西),但我已经碰壁了。 我拥有的是这样的东西
var s1 = blah
var s2 = blah
等等(到s7),然后是
var GPAresult = (s1 + s2 + s3 + s4 + s5 + s6 + s7)/7
这将获得该学期的GPA,这很好,除非我在下拉列表中选择“Study Hall”或“Dropped”,我必须得到变量。这两个选项返回一个值“Null”,然后通过上面的代码发送后转换为NaN,捣乱整个事物
所以我需要帮助制作的东西会丢弃默认为NaN的选项,然后除以合法值,如:
var GPAresult = (s1 + s2 + s3 + s4 + s5 + s6 + s7) / legalints
我可以让NaN返回零,我只需要帮助计算它们并从主管中减去它们
答案 0 :(得分:3)
我建议您使用数组而不是多个变量,这样您就可以执行某些操作。例如:
// Remove from the array all the items that aren't numbers
var numbers = [bla, bla, bla].filter(Number.isInteger);
// Sum all the numbers and store the result in the "sum" variable
var sum = numbers.reduce(function(a, b) {
return a + b;
});
// Perform the operation
var GPA = sum / numbers.length;
注意强> 此解决方案基于您希望从问题中说明的部门中减去无效数字的假设。
答案 1 :(得分:0)
试试这个:
<击> var GPAresult =((s1 + s2 + s3 + s4 + s5 + s6 + s7)/ legalints)|| 0; 击>
var GPAresult = ((s1 || 0) + (s2 || 0) + s3 + s4 + s5 + s6 + s7) / legalints;
答案 2 :(得分:0)
希望有用:
var s1 = "2";
var s2 = "3";
var s3 = "Study Hall";
var s4 = "4";
var s5 = "Dropped";
var s6 = "5";
var s7 = "6";
var legalints = 0;
var sum = 0;
for(var i= 0;i< 7;i++){
// variable construction does work for global variables only!
// please consider useing an array or better: read the results in this
// loop directly instead of into individual single variables
var point = parseInt(window["s" + (i+1)]);
if(!isNaN(point)){
legalints++;
sum += parseInt(point);
}
}
var result = sum / legalints;
检查&安培;余额一如既往地省略。
答案 3 :(得分:0)
这是一个小提示,显示你想要的东西,http://jsfiddle.net/4y5d6waL/
我评论了小提琴中的代码,但这里也是如此:
var s1 = 2;
var s2 = 3;
var s3 = 'bah';
// set 'GPAResult' to what the value the function returns, could take s4, s5, etc. as needed
var GPAResult = GPA(s1, s2, s3);
// Our function (note, it doesn't require any arguemnt)
function GPA(){
// set the number of classes and the current GradePoints to 0, which is what will return if none of the variables entered are numbers
var numberOfClasses = 0;
var GradePoints = 0;
// because we don't specify how many parameters, we are just itereating through every parameter that we give it
for (var i in arguments) {
// then, if the parameter isn't a string, such as 'StudyHall', we will add the value to our GPA variable, and step the numberOfClasses by 1
if(typeof arguments[i] != 'string'){
GradePoints += arguments[i];
numberOfClasses++;
}
}
// After iterating through every parameter entered, divides the GradePoints by the numberOfClasses, giving you the Grade Point Average
return GradePoints/numberOfClasses;
}
alert(GPAResult)