JRS: In article <31*************************@posting.google.com> , dated

Fri, 18 Mar 2005 10:02:32, seen in news:comp.lang.javascript, Matt

<bi*******@gmail.com> posted :

How do you add up all the values in an array? The length of the array

is variable. Is there a built in function?

No, but it is easy enough for the usual case.

For an array containing a Number in each position - an ordinary number

such as 3 or -4 or 5.67 or 1.234e5 - it's easy enough to write the code

each time, and any of these will do:

Tot = 0 ; for (J=0 ; J<A.length ; J++) Tot += A[J]

for (J=0, Tot=0 ; J<A.length ; J++) Tot += A[J]

Tot = 0 ; J = A.length ; while (J--) Tot += A[J]

The first is probably the most obvious, the last is probably the

fastest. If arrays are to be summed in that manner in many places in

the code, then it is worth making a function or method to do it.

If there is a possibility that some or all of the array entries are in

fact strings each representing a number in an obvious fashion, then

instead of Tot += A[J] one can use Tot += +A[J] .

If there is a possibility that any of the entries may be absent - not

zero, but missing, as in A = [1,,3] as opposed to A=[1,2,3] -

then *you* must decide what that represents. Is it right to skip the

missing entry as if it had not been there, or to treat it as present and

equal to zero (consequences differ if calculating an average), or to

consider that as an error needing to be reported? THE PROGRAMMER MUST

DECIDE - or be told ; it should not be left at the whim of someone

providing a "general" routine.

Similarly if there is a possibility that any of the entries is

definitely non-numeric, as in [1, "banana", 3].

Then an entry can be convertible to a number :

D = new Date("1970/01/02 00:00:00 GMT")

A = [1, D, 2]

for which Tot += A[J] gives "2Fri Jan 2 00:00:00 UTC 19701" and

Tot += +A[J] gives 86400003 ; IMHO, common sense suggests a

probable programming error.

Eschew rampant genericity.

--

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©

<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript

<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.

<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.