Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hot to sum all the elements in an array 2

Status
Not open for further replies.

ranta

Programmer
Jun 24, 2003
30
HI,

Is there any built in function within ASP that will allow you to sum all the elements in an array or do you have to loop through manualy?

 
you mean add them all up right?

I do not believe so. A loop will most likely be needed.

_____________________________________________________________________
Where have all my friends gone to????
onpnt2.gif

 
... I can't remember what the equivalent to the javascript "eval(expression)" is... but, in javascript, you could write:

Code:
var addStr = arrayVar.join("+");
var arraySum = eval(addStr);

So, if your arrayVar looked like: 1, 2, 3, 4...

your addStr would look like 1+2+3+4...

Evaluate the string and it ends up: 10.

I'm pretty sure there's a VBScript equivalent to "eval()", but someone else will need to point it out. Hope that helps a bit.
 
cool idea Mr3Putt

Dim val
Dim myarray : myarray = array("1","2","3")
val = eval(join(myarray,"+"))
response.write val

_____________________________________________________________________
Where have all my friends gone to????
onpnt2.gif

 
Thanks, onpnt,

It's less code than looping, anyway.. but it doesn't allow for any error-handling. So, if your array contains non-numeric or null values... it'll die.

Other than those caveats, it oughta work.
 
Also, I wonder how this method would handle negative values, like:

Code:
dim myArray : myArray = array("1","-2","3","4")

perhaps the join statement should be updated to look like:
Code:
dim val
val = eval("(" & join(myArray,")+(") & ")")
So, the "eval" function would receive a string like:
Code:
(1)+(-2)+(3)+(4)
...which might be a better idea.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top