M
Matt
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
is variable. Is there a built in function?
How do you add up all the values in an array? The length of the array
is variable.
No.Is there a built in function?
Matt said:How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
RobB said:Matt said:How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
There is now.
<script type="text/javascript">
Array.prototype.addNumbers = function(inclStrs)
{
var re = new RegExp(inclStrs ? '((number)|(string))':'number');
for (var i = 0,
l = this.length,
sum = 0,
n;
i < l;
++i)
{
if (re.test(typeof (n = this)))
sum += (!inclStrs) ? n :
/^[0-9]+$/.test(n) ? Number(n) : 0;
}
return sum;
}
</script>
How do you add up all the values in an array? The length of the array
is variable. Is there a built in function?
Dr said:JRS: In article <[email protected]>, dated
Fri, 18 Mar 2005 10:02:32, seen in Matt
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.
Eschew rampant genericity.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.