2013-05-16 5 views
-2

Si j'ai deux variables de somme avec des variables individuelles totales. Y at-il un moyen plus facile d'obtenir la somme?Ajouter des variables JavaScript plus efficacement?

Exemple:

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

Comment est-ce plus efficace? Il faut plus de temps pour taper, plus d'octets pour stocker, et la seule façon de l'implémenter consiste à utiliser un appel de fonction au lieu d'un simple opérateur! – Quentin

Répondre

10

Créer une fonction appelée sum()

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

Appelez il

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); 
Questions connexes