更有效地添加JavaScript变量?

时间:2013-05-16 14:29:47

标签: javascript math

如果我有两个和变量总和的和变量。是否有更简单的方法来获得总和?

示例:

var first_one = 5;
var first_two = 5;

var second_one = 5;
var second_two = 5;

var firstTotal = first_one + first_two;
var secondTotal = second_one + second_two;

var total = firstTotal + secondTotal;
return total;

2 个答案:

答案 0 :(得分:10)

创建一个名为sum()

的函数
function sum(val1, val2) {
    return val1 + val2;
}

称之为

var firstTotal = sum(first_one, first_two);
var secondTotal = sum(second_one, second_two);

var total = sum(firstTotal, secondTotal);

答案 1 :(得分:1)

function sum(a,b){
      return a+b;
}    
var firstTotal = sum(first_one, first_two);