Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #34311

Re: sum array

From Ben Bacarisse <ben.usenet@bsb.me.uk>
Newsgroups comp.lang.javascript
Subject Re: sum array
Date 2017-11-12 01:20 +0000
Organization A noiseless patient Spider
Message-ID <878tfcwaw9.fsf@bsb.me.uk> (permalink)
References <HM6dnRdhLcy-DJrHnZ2dnUU7-a3NnZ2d@westnet.com.au>

Show all headers | View raw


Andrew Poulos <ap_prog@hotmail.com> writes:

> To sum the integer elements in an array I'm using
>
> var sum = arr.reduce(function(a, b) {
>   return a + b;
> });
>
> which is fine. When I pass it
>   var arr = [,0, 1, -1, 3,, null];
> I get the correct answer though I'm expecting it to error. Why doesn't
>   it throw an error or at least not the right answer?

First, reduce only considers the elements that are present in the array,
and second, null is converted to +0 before the addition (non-string operands
of + are converted to number using the the ToNumber abstract operation).

-- 
Ben.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

sum array Andrew Poulos <ap_prog@hotmail.com> - 2017-11-12 11:09 +1100
  Re: sum array Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-11-12 01:20 +0000
  Re: sum array Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2018-02-14 09:57 +0100
    Re: sum array "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2018-02-15 12:12 -0800

csiph-web