[Javascript] If,while loop, for loop,function

loop js的圖片搜尋結果 
Conditional statement

Syntax:
if (      ) {

 // do this if condition value is true

} else {

 // do this if condition value is false

}

    Example

    var s = "a";
    
    if ( s == "a" ) {
    
     // will execute this block
     // as the condition expression is true
    
    
    } else {
    
     // will not execute this block
     // as the condition expression is not false
    
    }
    
    
    

 Iteration Statement

  • while loop

    Syntax:
      while ( true/false ) {
    
      }
    
    Example: Find the average of an array's elements
      var a = [1, 2, 3, 4];
      var sum = 0;
    
      var i = 0;    // 1. initialize a counter
      while ( i < a.length ) {      // 2. condition check
         sum = sum + a[i];
         i++;       // 3. increment counter (i.e. i = i + 1;)
      }
    
      var average = sum / a.length;
    
      console.log( average );
       //=> 2.5
    
  • for loop

    Syntax:
      for (     ;     ;     ) {
    
      }
    
    Example: Find the average of an array's elements
      var a = [1, 2, 3, 4];
      var sum = 0;
    
      for (var i = 0; i < a.length; i++; ) {
         sum = sum + a[i];
      }
    
      var average = sum / a.length;
    
      console.log( average );
       //=> 2.5
    

Functions

    Define a function

    function name() {
    // Our function code goes here.
    }
    
    e.g.
    // Define a function
    function add() {
     sum = 2 + 3;
     alert(sum);
    }
    
    // Call/Invoke/Execute the function foo
    add();
    

    Function returning a value

    // Use the keyword "return" to output
    function add () {
      var sum = 2 + 2;
      return sum;
    }
    
    // Call the function "add"
    result = add();
    alert(result); // This will alert "4"
    

    Function with arguments

    function add (a, b) {
      var sum = a + b;
      return sum;
    }
    
    // Call the function "add"
    result = add(2, 3);
    

    Alternative form

    // Create a variable called add and store a function in it.
    var add = function (a, b) {
      var sum = a + b;
      return sum;
    };
    
    // Call the function
    result = add(2, 3);

Comments