[Javascript] Array & Object

    object js array的圖片搜尋結果

    Array

  • Use index to access individual element:
    var a1 = [2, 5, 6, 8];
    
    var h1 = a1[0];  //=> h1 = 2
    var h2 = a1[2];  //=> h2 = 6
    
  • Use array's length property to check the number of element in an array
    var a1 = [2, 5, 6, 8];
    
    var h3 = a1.length //=> h3 = 4
  • Use array's forEach method to do something with each array element
    var a1 = [2, 5, 6, 8];
    
    var printIt = function ( x ) {
      console.log(x);
    };
    
    a1.forEach( printIt );
        // 1. forEach expects the argument,
        //    which is printIt in this example,
        //    being a function accepting an argument.
        // 2. Each array's element is used as argument to call "printIt"
        //    i.e. printIt(2), printIt(5), printIt(6), printIt(8)
    //=> 2
    //=> 5
    //=> 6
    //=> 8
    
  • More compact form (save the variable printIt)
    var a1 = [2, 5, 6, 8];
    
    a1.forEach( function ( x ) {
      console.log(x);
    });
    //=> 2
    //=> 5
    //=> 6
    //=> 8
    

 Example: (Array and Function)

Function calculating the average of the elements of an array of numbers
    // Define a function
    var average = function (array) {
        var sum = 0;

        array.forEach( function(x) {
            sum = sum + x;
        });

        return sum/array.length;
    }

    var a = [1, 2, 3, 4];

    // Call the function with an array and save the returned value
    var result = average(a);

    console.log(result);
    //=>2.5

 Object

  • as collection of key/value (or property/value) pairs
    Example:
      object = { key1:value1, key2:value2, ... };
      
  • use dot notation to access the value of an object's property
    Example:
      object.key1
      
  • array of objects
    i.e.
      [ {  }, {  }, ... ]
      
  • Example:
      Array:
      var book   = [ "JavaScript", "CSS", "HTML"];
      var year   = [ "2010", "2012", "2015"];
      var price  = [ 350, 240, 138];
    
      Object:
      var book1 = {"bookName":"JavaScript", "pubYear":"2010", "listPrice":350};
      var book2 = {"bookName":"CSS", "pubYear":"2012", "listPrice":240};
      var book1 = {"bookName":"HTML", "pubYear":"2015", "listPrice":138};
    
      Array of Objects:
      var books = [ {"bookName":"JavaScript", "pubYear":"2010", "listPrice":350},
                    {"bookName":"CSS", "pubYear":"2012", "listPrice":240},
                    {"bookName":"HTML", "pubYear":"2015", "listPrice":138}
                   ];
    
       i.e.  var books = [ book1, book2, book3 ];
    
      books[1].bookName
        //--> "CSS"

Comments