2013-05-16 59 views
-2

如果我有兩個總變量與總個體變量。有沒有更容易的方法來獲得總和?更有效地添加JavaScript變量?

例子:

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; 
+3

如何是更有效?鍵入時間較長,需要存儲更多字節,實現它的唯一方法是使用函數調用而不是簡單的操作符! – Quentin

回答

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
function sum(a,b){ 
     return a+b; 
}  
var firstTotal = sum(first_one, first_two);