Quote:
Originally Posted by DaveyErwin
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.