View Single Post
Old 01-04-2013, 10:16 PM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,555
Thanks: 62
Thanked 4,054 Times in 4,023 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Quote:
Originally Posted by DaveyErwin View Post
function addOne(element, index, array) { return ++array[index]; }
var Aarr = [0,1,2,3,4,5,6,7,8,9];
Aarr.filter(addOne);
alert(Aarr);
Well, yes. That will increment each element of the array by one.

But you would get the same results using
Code:
function addOne(element, index, array) 
{ 
    ++array[index]; 
    return false; // or return Math.random() < 0.5; even 
}
The return value from filter has no impact on what happens in the *original* array.

If you were to do this:
Code:
function addOne(element, index, array) { return ++array[index]; }
var Aarr = [0,1,2,3,4,5,6,7,8,9];
var Barr = Aarr.filter(addOne);
alert(Aarr + "\n" + Barr);
You would find that Barr will contain a copy of the *original* array (0 through 9) while Aaar has every element incremented by one.

But, again, if you started with (say)
Code:
var Aarr = [0,1,-1,3,-1,7,0];
Then you would end up with
Code:
Aarr == [ 1,2,0,4,0,8,1 ]
Barr == [ 0,1,3,7,0 ]
Because the -1s on being increment become zero and so the return from filter is, effectively, false and those -1s get filtered out.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote