Javascript Arrays

  • Storing lots of data at once
    • The variables I have used to this point store a single piece of information
      • Number, String, Boolean, or Object
    • What do you do if you want multiple, related piece of information?
    • Store them in arrays
  • Declaring An Array
    • Declaring an array
      • var grades=[80,87,94,82,62,98,81,81,74,91];
      • var foods = ['bananas', 'apples', 'pizza'];
      • var images = document.getElementsByClassName['imgs'];
      • var listItems = document.getElementsByTagname['li'];
  • Arrays
    • An array is a collection of values

      未命名_2017-01-03_11-10-03.png

    • Accessing An Array
      • Each value is called an element
      • Elements are referenced by index
      • grades[0] refers to value 80 (1st value)
      • grades[4] refers to value 62 (5th value)
    • The elements in the array DON’T have to be all the same type
      • var info=["Collean", 1715, "Walnut", 44004];
  • JavaScript Arrays are Objects
    • They have attributes and methods
    • grades.length
    • grades.sort()
    • grades.push(element)
      • grades[grades.length] = element
  • Review
    • Learning to declare and manipulate arrays will make your code more powerful
    • We can now play with new API methods:
      • getElementsByTagName('t');
      • getElementsByClassName('c');

Code with Me – Arrays

  • Arrays
    • Can you?
      • Declare an Array?
      • Access the Different Elements of an Array?
      • Add Elements to an Array?
  • Example
    • JS-Add Fruit

Javascript Iteration

  • Faster accessing of Arrays
    • The upside of arrays is that they can store a lot of data
    • The downside of arrays is that they can store a lot of data
    • What do you do if you wan tot access all of it?
  • Iteration/Looping
    • The best way to access all data in an array is with iteration, also called “looping”
    • When you loop through an array you look at each element, usually starting at 0 and ending at the last element
  • Finding the Average
    • 80 87 94 82 62 98 81 81 74 91
      0 1 2 3 4 5 6 7 8 9
    • What would you do if you wanted to find the average of all the grades?
    • Sum up all of the elements and then divide by the number of elements
  • for loop
    • We will use a for loop
    • The syntax is:
      for (j = 0; j < array.length; j++) {
          // The steps in here are repeated
      }
      
  • Breaking Down the for Loop
    • Start with the keyword for
    • Set a variable to the initial value
      • (usually index=0, counter = 0, or i = 0)
    • Run a boolean test case (true/false)
    • Run the code
    • Update your variable, and go back to 2
  • 未命名_2017-01-03_11-23-46.png

  • example
    for (index = 0; index < array.length; index++) {
       document.write(array[index]);
    }
    
    • If the array has 10 elements, the for loop will run 10 times and stop as soon as index = 10
  • Finding the Average
    var sum = 0;
    for (index =0; index < grades.length; index++) {
       sum += grades[index];
    }
    document.write(sum/grades.length);
    
  • Loop breakdown
    • Why use grades.length in stead of “10”
    • What would happen if you subtracted 1 instead of adding 1?
    • What would happen if the condition was set to index <= grades.length?
  • Review
    • Looping is used for much more than arrays!
    • You can loop from low number to high number, high number to low number, or even just a subset
    • Once again, practice, practice, practice

Flow of Control

  • Dynamic Execution
    • Sometimes it is helpful to put decision points into your code
      • Add some variety to the program
      • React to good/bad user input
      • Avoid potential errors
  • Flow of control
    • Break your program into blocks
    • Efficient algorithms execute only the blocks needed
    • The execution of these blocks is called flow of control
  • Decision Points
    • When we wrote the for loop earlier, we set up a decision point
      • End of array? Stop Summing
      • Not? Add the next number
    • There are other methods for changing flow of control
  • if
    • An if statement evaluates a Boolean expression before performing an action
      • If expression is true, execute code
      • If expression is false, skip it
        if (boolean-expression) {
           //steps to perform
        }
        
  • Syntax and Logic of the if statement

    未命名_2017-01-03_13-25-04.png

  • Blocks
    • In JavaScript, statements enclosed in curly brackets {…} are considered a single statement
    • Indentation is not required, but it very important for readability

      未命名_2017-01-03_13-28-23.png

  • Example
    • JS – if with Name
    • JS – Array Average with zero
  • else statement
    • An else can be added to an if statement to make an if-else statement
      if (boolean)
         //  statement 1;
      else
         // statement 2;
      
    • If the condition is true, statement 1 is executed
    • If the condition is false, statement 2 is executed
    • One or the other will be executed, but not both

      未命名_2017-01-03_13-31-37.png

  • Example
    • JS – if with Name
    • JS – Array Average with zero
  • Review
    • Use if to specify a block of code to be executed, if a specified condition is true
    • Use else to specify a block of code to be executed, if the same condition is false

Code with Me – Combining Loops and Conditionals

  • Complex Boolean Situations
    • Can you?
      • Identify where you need decision points
      • Update existing code to give the best answer?
  • Example
    • JS – Array Average With Undefined Elements

Advanced Conditionals

  • Complex Boolean situations
    • Decision points aren’t always simple
      • What if you need to check for two conditions?
      • What if one condition depends upon the value of another?
  • Nested If Statement
    • It is possible to “nest” statements
      • Put one statement inside another – different from part of the same block
        if (boolean-expression) {
          // statements;
          if (new-boolean) {
            // statements to execute if both true;
          }
        }
        
  • Please, please, please
    • Careful planning is key to making sure you get the desired results
  • What about else statements?
    • An else statement always matches the most recent open if statement
    • Indentation has nothing to do with it
  • Example
    • JS – nested if with Name
    • JS – Inefficient code
  • Review
    • It is possible to create complex flow-of-control in a program
    • Understanding this code is crucial, writing it yourself … not so much

Common Error

  • Debugging Your JavaScript Code
    • Browsers try to hide your JavaScript errors, so you need to seek them out
    • Two classes of errors
      • Syntactic
      • Logic
  • Syntactic Errors
    • These errors break the “rules” of JavaScript
      • Type something wrong: getElementsById()
      • Forgot to close a curly bracket: {…
      • Using an undefined variable
    • Will appear in the browser console if you are on a laptop/desktop
      • unfortunately not available on mobile devices
  • Logical Error
    • Your code is valid, but there is something wrong with your thought process
      • In the Array Average example you didn’t check for zero or you used the length of array in stead of count
    • Some “logic” errors really are typos.. they are just typos that run
  • Issues with Comparisons…
    • Don’t forget
      • 5 == '5'~ is true
      • if(name="Collean") wants to assign a value, not check for equality
      • (age>65) && (18>age) will NEVER BE TRUE…
      • (age>65) || (age>18) is silly, you only need to check the second condition
  • Concatenation vs Addition
    • The + operator performs different actions based on the type..
      • 5 + 5 -> 10
      • ‘5’+’5′ -> ’55’
      • ‘5’+ 5 -> ’55’
    • This isn’t always bad!! Sometimes you want to concatenate a string and a variable
      • src = "url(" + img.src + ")";
  • Issues with Nesting
    • Make sure that your else statements match with the appropriate if
    • Make sure you don’t end your flow of control by misplacing semicolons;
    • if(age<18); alert("Too young");
    • for(c=0, c<5; c++); document.write(c);
  • Review
    • Whenever possible, use the console
    • Think about your code before you write it.
    • Code and test, code and test, Saving often!
    • Ask for help, Someone else can often see your errors more quickly
Notice: compact(): Undefined variable: limits in /var/www/html/wp-includes/class-wp-comment-query.php on line 853 Notice: compact(): Undefined variable: groupby in /var/www/html/wp-includes/class-wp-comment-query.php on line 853

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *