Client side programming

This week: Chapter 4

Till next week:
Read chapter 5

Any questions from previous weeks?

Arrays

Why did the programmer quit his job?

–He didn't get 

var fruit1 = "lime"
var fruit2 = "banana"
var fruit3 = "cherry"
var fruit4 = "orange"
var fruit5 = "grapes"
var fruit6 = "mango"
var fruit7 = "pear"
var fruit8 = "kiwi"
var fruits = [
  "lime",
  "banana",
  "cherry",
  "orange",
  "grapes",
  "mango",
  "pear",
  "kiwi"]

Many variables

One variable

An array is a list of values

Billboard

0. Someone You Loved
1. Truth Hurts
2. Senorita
3. Circles
4. No Guidance
5. Panini
6. HIGHEST IN THE ROOM
7. Ran$om
8. Bad Guy
9. 10,000 Hours

var billboard = [ 
  'Someone You Loved',
  'Truth Hurts',
  'Senorita',
  'Circles',
  'No Guidance',
  'Panini',
  'HIGHEST IN THE ROOM',
  'Ran$om',
  'Bad Guy',
  '10,000 Hours' 
];
billboard[3] // 'Circles'

But in javaScript 1'st place is 0

When do you need arrays?

  1. When you don't know beforehand how many values you need to save.
  2. When you have a large number of values that needs to be saved.
  3. I you need to save info in the form of rows and columns, a 2d array is useful. 

When you don't know beforehand how many values you need to save.

[false, true, false, false, false, true, true, false, false...]

When you have a large number of values that needs to be saved.

var student01 = 4;
var student02 = 4;
var student03 = 5;
var student04 = 4;
var student05 = 3;
var student06 = 5;
var student07 = 3;
...
var student64 = 4;
var student65 = 3;
students = [4, 4, 5, 4, 3, 5, 3, 4, 3,...];

Too many variables

Convenient with only one variable

Save info in rows and columns (2D array)

var ticTacToe = [
  ['x','o',' '],
  [' ','x',' '],
  [' ',' ','o']
]
ticTacToe[0][1] // 'o'

Another mental model of an Array

A storage shelf with numbered spots

Create an empty array

var fruits = [];

Why create an empty array?

You might want to add stuff to it later, one element at a time.

(I will show you soon)

Create an array with elements

var fruits = ["apple", "banana", "cherry"];

0        1       2

page 128

access an element in an array

var myBanana = fruits[1];
var fruits = ["apple", "banana", "cherry"];

0        1       2

page 129

counting elements in an array

var fruits = ["apple", "banana", "cherry"];
var howMany = fruits.length; // 3

.length is a property all arrays have

(just like strings)

page 130

Type: Array

A LIST OF MULTIPLE VALUES

var fruits = ["apple", "banana", "cherry"];

var fibonacci = [0, 1, 1, 2, 3, 5, 8, 13];

var conditions = [true, false];

var mixed = ["Everything", 42, true];

Arrays
(subtype of object)

types

foo = 42;
baz = 3.1415;
foo = "Hello";
baz = 'world!';
foo = true;
baz = false;
fruits = [
  "apple",
  "banana", 
  "cherry"
]

NEW!

how to populate an array

1.

2.

3.

//populate it from the start:
var circles = ['green', 'green', 'green', 'green'];
// Built in method push, adds to the end of the array
circles.push('red');
// unshift, adds to the beginning of the array
circles.unshift('red');

4.

//Specify a position 
circles[4] = 'red';

how to remove from an array

1.

2.

3.

// pop removes the last element
circles.pop();
// shift, removes the first element
circles.shift();
// weird quirk
circles.length --

4.

// remove 1 at position 3
circles.splice(3,1); 

More built in functions

Sort alphabetically

fruits.sort(); // ["apple", "banana", "cherry"];

Search for an item #1

fruits.includes('cherry'); // true

Search for an item #2

fruits.indexOf('cherry'); // 0
var fruits = ["cherry", "banana", "apple"];

Array.sort(fx)

advanced

var guesses = [40, 60, 50 , 45, 47, 48];
guesses.sort(compareNumbers);

function compareNumbers(a, b) {
  return a - b;
}

array1.concat(array2)

returns a new combined array

/******************************
  Array.concat() -Combine Two Arrays
******************************/
var pair = ["J", "J"];
var threeOfAKind = ["9", "9", "9"];
var fullHouse = pair.concat(threeOfAKind);
/******************************
 pair:         ['J', 'J']
 threeOfAKind: ['9', '9', '9']
 fullHouse:    ['J', 'J', '9', '9', '9']
******************************/

splice()

 changes an array by removing items

/******************************
  Array.splice(2,1) means:
  Go to index 2, 
  remove 1 item 
  and return it (as an array).
******************************/

var fishes = ["shark", "salmon", "dolphin", "cod"];
var mammals = fishes.splice(2, 1);

/******************************
  fishes: ['shark', 'salmon', 'cod']
  mammal: ['dolphin']
******************************/

you can do even more with splice

tricky but useful method

/******************************
  Splice can also
  Remove multiple items and  
  Add new items:
******************************/
var pokerHand = ["10", "10", "10", "J", "8"];
var unwanted = pokerHand.splice(3, 2, "A", "A");
/******************************
  pokerhand: ["10", "10", "10", 'A', 'A']
  unwanted: ['J', '8']
******************************/

Let's combine them

var fishes = ["shark", "salmon", "dolphin", "cod"];

if( fishes.includes("dolphin") ) {
  
  let dolphinPosition = fishes.indexOf("dolphin");
  
  fishes.splice(dolphinPosition , 1 );
  
}

deal with all values from an array

even if you don't know how many elements there are

loops

of course

while

var fruits = ["kiwi", "mango", "orange", "banana", "apple"];

var index = 0;

while (index < fruits.length) {

    console.log( fruits[index] );
    index++;

}

...as you know

for

is a compressed form of while

for-loop template:

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

for ( var i = 0; i < array.length; i++ ) {
    //array[i]
}
  • Open an editor and try to code it without looking
  • LEARN THIS BY HEART

page 140

Finding and changing HTML-code

Finding elements

document.querySelector("#main-menu") 
<header>
  <nav id="main-menu"> <!-- this and all it's children -->
    <ul>
      <li>home</li>
      <li>about</li>
    </ul>
  </nav>
</header>

document.querySelector() returns the first element that match the CSS-selector-string passed in.

change the content of an element

<div id="demo">
<h1>Existing content</h1>
</div>
var myDiv = document.querySelector('#demo');

myDiv.innerHTML = '<p> This is <em>new</em> content </p>';

Existing content

This is new content

 

<div id="demo">
<p> This is <em>new</em> content </p>
</div>

before

after

Browser output

Browser output

Starbucks order

using arrays and push/shift

var orders = [];

function newOrder(item) {
  orders.push(item); // add to bottom
}

function removeOrder() {
  orders.shift(); // remove from top
}

Try it out! 

Add and remove orders too see what happens.

clone an array

// You cannot copy arrays like you do with strings and numbers
x = 10;
y = x;
x = 32;
console.log( x+y ) // 42 not 64

foo = [3,2,1];
bar = foo;
bar.sort();
console.log(foo); // [1,2,3]
console.log(bar); // [1,2,3]


// This is a way to create a copy of an array

foo = [3,2,1];
bar = foo.slice(0);
bar.sort();
console.log(foo); // [3,2,1]
console.log(bar); // [1,2,3]

strings are a bit like arrays

// some array methods apply to strings as well
"hello world".length // 11
"hello world".indexOf("w") // 6


// strings can be converted to arrays .split(separator)
"hello-world".split("-") // ["hello", "world"]
"code".split("") // ["c", "o", "d", "e"]


// Access a letter from a string
var foo = "hello world";
var bar = foo[6]; // "w"

from string to array to string

var myString = "The weather is lovely in Sweden";
var myArray = myString.split(" ");
// ["The", "weather", "is", "lovely", "in", "Sweden"];

myArray[3] = "aweful";
// ["The", "weather", "is", "aweful", "in", "Sweden"];

myString = myArray.join(" ");
// "The weather is aweful in Sweden"

console.log(myArray.join("-"));
// "The-weather-is-aweful-in-Sweden"

What can we actually use arrays for?

Like in web design?

JS5

By Johan Kohlin

JS5

Arrays

  • 797