Javascript Addition Problem

Djcottrell

New Member
Messages
29
Reaction score
0
Points
0
I am a php programmer and I am just starting to learn the Javascript functions. For some reason I can not figure this one out.

A little about this code. The saves array is generated by a php include. Long story short the value of save1-5 is a decimal number such as 1.0, 1.5, 2.0, 2.5. This is being used for a review system. I am trying to collect the values of save1-5 and averaging them out.

Lets say x=0.5 and y=1.5. If i add x+y I dont get 2 i get 0.52.5

Is there an easier method in which to create this in JS.

Code:
[COLOR=#000000][FONT=monospace]var saves = new Array('save1','save2','save3','save4','save5');[/FONT][/COLOR]
for(var i in saves){	
     var y = eval(saves[i])*1;		
     x=x+y; 
}
var arraySize = saves.length;
var average = x/arraySize;
var result = average.toFixed(1);
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Code:
var saves = new Array('save1','save2','save3','save4','save5');

If that is generated by PHP, why not just generate numbers instead of strings?

EDIT/ADD:

If you must have strings...

Code:
var x = 0;
var saves = Array( '1.1', '2.2', '3.3');
for(var i in saves){	 	
     x=x+ 1*saves[i]; }
 
Last edited:

Djcottrell

New Member
Messages
29
Reaction score
0
Points
0
Code:
[LEFT][COLOR=#333333]var saves = new Array('save1','save2','save3','save4','save5');[/COLOR][/LEFT]

There is no limit to the number of saves. In another section of the js it creates custom jquery functions for each save. Within those functions is saves a variable to each of the saves.

This code pulls those values and creates the average between all the ratings.

Anyway I created a fix for my problem. I dont know if it is the best method but it works.

Code:
for(var i in saves){	     var y = eval(saves[i])*10;
     x=parseInt(x)+parseInt(y); 
}
var arraySize = saves.length;
var average = parseInt(x)/arraySize;
var result = average/10;
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
What, exactly, is the problem? What do you want/expect to happen? What actually happens? You should always include this information when asking for help.

A few comments:

If eval() is the answer, you’re almost certainly asking the wrong question.
Instead of separate variables, store the values in an array or object. Then loop over that, instead of saves (or make saves store the data). If you absolutely, positively must use separate variables (and I would still question the necessity) and they're globals (which is bad for its own reasons), access them as properties of the global object, window: window[saves[i]].

Instead of some custom way of generating JS from PHP (which it looks like you're using), try json_encode.

PHP:
<?php $saves = array(1.0, 1.5, 2.0, 2.5); ?>
var saves = <?php echo json_encode($saves) ?>;
 
Top