7/07/2013
8:57:00 PM 0

Javascript loop

  1. for
    var myArray = [1,2,3];
    for (var i = 0; i < myArray.length; i++) 
    {
        alert(myArray[i]);
    }
    
    output
    --------------------------------------------
    1
    2
    3

  2. for in
    var obj = 
    {
        a : 1,
        b : 2
    };
    
    for(var key in obj) 
    {
       alert(key);
    }
    
    output
    --------------------------------------------
    a
    b

  3. forEach (IE9 之後才支援)
    forEach 是從 Array.prototype.forEach 來的, 因此只要是 Array 物件就擁有 forEach 方法
    function alertElements(element, index, array) 
    {
        alert(element);
    }
    [1,2,3].forEach(alertElements);
    
    output
    --------------------------------------------
    1
    2
    3

    在 ECMAScript 5, 也可使用 forEach 取得物件屬性名稱
    var obj = 
    {
        a : 1,
        b : 2
    };
    
    Object.keys(obj).forEach(function(key) 
    {
        alert(key);
    });
    
    output
    --------------------------------------------
    a
    b

  4. while
    var i=0;
    var myArray = [1,2,3];
    
    while(myArray[i])
    {
        alert(myArray[i]);
        i++;
    }
    
    output
    --------------------------------------------
    1
    2
    3

  5. do while
    var i = 1;
    var sum = 0;
         
    do 
    {
        sum += i;
        i++;
    } 
    while (i <= 100);
    
    alert(sum);
    
    output
    --------------------------------------------
    5050

0 comments:

Post a Comment