Saturday, January 8, 2011

Looping through an array in Javascript

A little bit confused with Javascript array. I was.

Mastering Javascript Arrays

function  LoopingTroughArray() {
 
     var  Values = ["A" ,"B" ,"C" ];
                                 
     for  (var  i = 0; i < Values.length; i++) {  // Solution 1 
 
         alert(Values[i]);
     }
                 
     for  (var  index in  Values) { // Solution 2 
 
         alert(Values[index]);
     }
                 
     jQuery.each(Values,         // Solution 3 with jQuery 
                 function (index, value){ 
                     alert(value); 
                     // return true;  same as continue 
                     // return false; same as break 
                 } 
     );
     // The array method forEach is supportted in FireFox but not in Internet Explorer. 
 }
 
 function  FilteringAnArray() {
 
     var  Values    = [1,2,3];
     var  NewValues = jQuery.map( Values,
                                 function  (value){
                                     if  (value > 2)                                
                                         return  value;                                
                                     else 
                                         return  null ; // remove the item from the array 
                                 }
     );
     alert(NewValues.valueOf());
 }
 
 function  ChangingTheContentOfAnArray() {
 
     var  Values    = [1,2,3];                                
     var  NewValues = jQuery.map( Values,
                                 function (value){                                 
                                 return  value*2;
                                 }
     );
     alert(NewValues.valueOf());                
 }
 
 function  LoopingTroughAnObjectProperties() {
 
     var  Person = {
         LastName:   "Descartes" ,
         FirstName:  "Rene" 
     }
                 
     jQuery.each(Person,
         function (key, value){ 
             alert(key+"=" +value);
         }
     );                
 }
 
 

No comments:

Post a Comment