jcadima
10/16/2015 - 5:37 AM

Get Size of Object array, display size of object array, use for loop

Get Size of Object array, display size of object array, use for loop

REF:
http://stackoverflow.com/questions/5223/length-of-a-javascript-object-that-is-associative-array


yt_players={} ; // object array
var elem = 0 ;

// YT.Player will create objects, notice the declaration above,
jQuery(".ytplayer").each(function() {
            yt_players[elem] = new YT.Player(this.id); // put the IDs in a numeric array instead of their names
       
        elem++;
});


// in orde to print the object array size and use it in a for loop we would do this
console.log('players size: ' +  Object.keys(yt_players).length ) ;


and to use it in a for loop

jQuery('.btn_close').on('click', function(){
  for ( var i = 0; i < Object.keys(yt_players).length ; i++ ) {
      yt_players[i].pauseVideo();
  }
				    
instead of doing this:

yt_players[0].pauseVideo();
yt_players[1].pauseVideo();
yt_players[2].pauseVideo();
yt_players[3].pauseVideo();
yt_players[4].pauseVideo();
yt_players[5].pauseVideo();
yt_players[6].pauseVideo();
yt_players[7].pauseVideo();