What we will cover in class

  • Ch. 12 String Basics
  • Ch. 14 Array Basics
  • Array applications

Definition:
An Object is a set of Properties

Some properties are functions => Methods

        //Examples
        Math.PI
        Math.random()

        "aeiou".length
        "aeiou".charAt(2)
        "aeiou".charAt(2).toUpperCase()
      

Fig. 12.2: How strings are represented in memory

Strings are arrays of characters

Strings and Arrays use zero-based indexing

Description

Processing a String?


Use a for loop

P. 124:


  • Access all characters in your string by looping through the index positions.


  • The start of the loop will be 0, and the end of your loop will be determined by the length of your string.


  • The length of a string (aka a count of the number of characters) is returned by the length property.

Here is an example (p. 125)


This loop visits every character in the string

let vowels = "aeiou";

//traverse string from 0 to length - 1
for (let i = 0; i < vowels.length; i++) {
    alert(vowels[i]);   //array subscript operator
}
      

String Processing, Example 1

Count the vowels

        //recognizer for vowels
        var isVowel = function(ch){
            //https://www.kirupa.com/html5/the_devowelizer.htm
        };

        //count the vowels in a sentence
        var countVowels = function(s){
            //initialize a counter
            var count = 0;
            //traverse string
            for(var i = 0; i < s.length; ++i){
                if(isVowel(s.charAt(i))    //array subscript operator
                    ++count;
            }
            return count;
        };
      

String Processing, Example 2

Get the vowels

        //recognizer for vowels
        var isVowel = function(ch){
            //https://www.kirupa.com/html5/the_devowelizer.htm
        };

        //return all the vowels in a string
        let getVowels = function(s){
            let result = "";
            //traverse the string
            for(let i = 0; i < s.length; ++i){
                if(isVowel(s[i])    
                    result = result + s[i];
            }
            return result;
        };
      

String Processing, Example 3


=> Week 5 Lab

Write and test a function named countOccurrences that accepts two arguments (a string and a character) and counts the number of times the character appears in the string.

countOccurrences(“Alpha”, “a”) => 2

countOccurrences



        let countOccurrences = function(s, ch){
            //initialize a counter
            let count = 0;
            //traverse the string
            for(let i = 0; i < s.length; ++i){
                if(the current char in s is equal to ch)    
                    add 1 to count
            }
            return count;
        };
      

String Methods (Ch. 12)

Ch. 14, The Array Object

Description
Ch. 14

Creating Arrays: Array Literals

Accessing Array Elements: Subscript Operator ([ ])

Examples:

var groceries = ["Milk", "Eggs", "FrostedFlakes", "Salami", "Juice"];

var result = "";
var item;

for (var i = 0; i < groceries.length; ++i) {
    item = groceries[i];
    result = result + " " + item.toUpperCase();
}

console.log(result);   // MILK EGGS FROSTEDFLAKES SALAMI JUICE

  

Accessing Array Elements

let primes = [2, 3, 5, 7];
console.log(primes[0]);                 // 2
console.log(primes[0] + 1);             // 3
console.log(primes[0] + primes[1]);     // 5
console.log(primes[primes[1]);          // 7
  

Writing Functions that Accept Array Arguments

let sumArr = function(arr){
  let sum = 0;
   //sum all numbers in array
   for(let i = 0; i < arr.length; ++i){
      sum += arr[i];
   }
   return sum;
 };
  

Add to the end of an Array: [ ]

let groceries = ["Milk", "Eggs", "FrostedFlakes"];

groceries[3] = "Spam";
console.log(groceries);    // ["Milk", "Eggs", "FrostedFlakes", "Spam"]
                           // -> inspect the array in the console
  

Add to the end of an Array: push()

let groceries = ["Milk", "Eggs", "FrostedFlakes"];

groceries.push("Spam");    
console.log(groceries);   // ["Milk", "Eggs", "FrostedFlakes", "Spam"]
  

Remove from the end of an Array: pop()

let groceries = ["Milk", "Eggs", "FrostedFlakes", "Spam"];
let e; 

//remove element from end
e = groceries.pop();
console.log(e);             // "Spam"
console.log(groceries);     // ["Milk", "Eggs", "FrostedFlakes"]
  

Remove from the front of an Array: shift()

let groceries = ["Milk", "Eggs", "FrostedFlakes", "Spam"];
let e; 

//remove initial element 
//delete, and shift left
e = groceries.shift();
console.log(e);             // "Milk"
console.log(groceries);     // ["Eggs", "FrostedFlakes", "Spam"]
  

Add to the front of an Array: unshift()

let groceries = ["Eggs", "FrostedFlakes", "Spam"];
let e; 

//add new element at front
//shift right, and insert
groceries.unshift("Milk");
console.log(groceries);     // ["Milk", "Eggs", "FrostedFlakes", "Spam"]
  

Pop, Push, Shift, and Unshift are Mutators

The array itself is changed

  

Find the index of an item in the Array

let groceries = ["Milk", "Eggs", "FrostedFlakes", "Spam"];
let pos = groceries.indexOf('Spam');
console.log(pos);  // 3

pos = groceries.indexOf('FruitLoops');
console.log(pos);  // -1
  

Array Processing Examples

Prime Numbers

Find the prime numbers between 1 .. n

let getPrimes = function(n){
  let primes = [];
  for(let i = 2; i <= n; ++i){
    if(isPrime(i))
      primes[i] = i;
  }
  return primes;
};

let primesArr = getPrimes(10);
console.log(primesArr);  // [empty, empty, 2, 3, empty, 5, empty, 7]
  

Modifications

  • Modify getPrimes so that it returns an array with no empty elements

  • Modify getPrimes so that it returns the number of primes between 1 .. n. Name it countPrimes.

Array Processing Examples

Rolling Dice

Rolling Two 6-Sided Dice

36 possible combinations:

Rolling Two 6-Sided Dice

Probabilities of rolling N:

(ways of rolling N / 36)

Roll a Die

let rollDie = function() {
  return Math.floor(Math.random() * 6) + 1;
};

let die1 = rollDie();
let die2 = rollDie();
let num = die1 + die2;
console.log(num);
  

Array Processing Examples

Rolling Dice

  • Roll the dice n times

  • Store a count of each number rolled, in an array

Q: How should we declare the array to hold rolls of 2 .. 12?

Count the times each number is rolled

let rollDice = function(n) {
  //array to hold dice rolls. 1st two elements not used (rolls of 0 and 1)
  let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  //let arr = new Array(13).fill(0);
  let die1, die2, num;

  //roll dice n times
  for (let i = 1; i <= n; ++i) {
    die1 = rollDie();
    die2 = rollDie();
    num = die1 + die2;
    ++arr[num];      //add 1 to the times we rolled num
  }
  return arr;
};
  

What We Covered in Class

  • Ch. 12 String Basics
  • Ch. 14 Array Basics
  • Array applications
HTML, CSS & JavaScript are the three pillars of Web Standards.

http://blogs.uoregon.edu/cis11schedule/