调用此方法时 knownScore = 70, newScore = 70, 深度= 1, 它返回3535 !!!!! 这怎么可能?
this.weightedAvg = function(depth, knownScore, newScore) {
if ((knownScore > 100) || (knownScore < -100)) return newScore;
else return Math.round((depth*knownScore + newScore)/(depth + 1));
};
当使用值35,70,2调用时,它返回2357! 有什么帮助吗?
答案 0 :(得分:3)
您传递给该函数的newScore的值是一个字符串。你应该确保它们都是数字。此代码将起作用(请注意将newScore转换为数字的+号):
this.weightedAvg = function(depth, knownScore, newScore) {
if ((knownScore > 100) || (knownScore < -100)) return newScore;
else return Math.round((depth*knownScore + +newScore)/(depth + 1));
};
更多详情:
70 + '70' // this is string concatenation instead of addition, results in 7070
当结果除以2时,结果将转换为数字:
'7070'/2 // converts to number, resulting in 3535
答案 1 :(得分:2)
您需要将var解析为数字,如下所示:
var number1 = Number(n);
你传递字符串所以他做“2”+“35”+“70”而不是2 + 35 + 70!