View Single Post
Old 01-05-2013, 01:45 AM   PM User | #11
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,764
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
Question

Well, you've managed to confuse the fool out of me.

I started out trying to figure out the .filter() function,
but have abandoned that because I thought I understood your Array.prototype function.

Now I don't understand what's happening with your latest modification with the 'callback' addition.

Here is the test code I am using to try to understand the working.
In the comment section at the end, I list what I expected and what is displayed.
??? indicates that I don't understand the results.

If you have the time, now that you have fogged my prior clarity, could you explain the
difference between what I thought I know and what is really happening?
(I may be testing your mind reading skills with that last statement).

Code:
<script type="text/javascript">
Array.prototype.forEach = function( callback ) {
  var ar = [];
  for ( var i = 0; i < this.length; ++i ) {
    ar[i] = ( callback == null ) ? this[i] : callback( this[i], this, i );
  }
  return ar;
}

var Aarr = [0,1,2,3,4,5,6,7,8,9];

var Barr  = Aarr.forEach( function(element) { return element + 1; } );
var BBarr = Aarr.forEach( function(element, array, index) { array[index] += 1; return element; } );
var Carr = Barr.forEach( );
var Darr = Aarr.forEach( );
var Earr = Aarr.forEach( function(element, array, index) { array[index] *= 100; return element; } );

alert('A : '+Aarr + "\nB : "+Barr +'\nBB: '+BBarr + "\nC : "+Carr + "\nD : "+Darr + "\nE : "+Earr +"\nA : "+Aarr);

/*
    Expected to see:
A : 0,1,2,3,4,5,6,7,8,9
B : 1,2,3,4,5,6,7,8,9,10
BB: 1,2,3,4,5,6,7,8,9,10
C : 1,2,3,4,5,6,7,8,9,10
D : 0,1,2,3,4,5,6,7,8,9
E : 0,100,200,300,400,500,600,700,800,900
A : 0,1,2,3,4,5,6,7,8,9
 
    Actual display:
A : 100,200,300,400,500,600,700,800,900,1000   ???
B : 1,2,3,4,5,6,7,8,9,10
BB: 0,1,2,3,4,5,6,7,8,9                        ???
C : 1,2,3,4,5,6,7,8,9,10
D : 1,2,3,4,5,6,7,8,9,10                       ???
E : 1,2,3,4,5,6,7,8,9,10                       ???
A : 100,200,300,400,500,600,700,800,900,1000   ???

*/
</script>
jmrker is offline   Reply With Quote