Johan Kohlin
Lecturer at School of engineering, Jönköping University.
slides.com/jkohlin/js-4/live
Till next week: Read chapter 5
the step where the computer finds all variable declarations first
before any assignments are made
baz = foo;
var foo = 12;
var baz;
//Both foo and baz are 12.
//This works because of the hoisting step
// After hoisting:
var baz;
var foo;
foo = 12;
baz = foo;
// Hoisting --> You code is rearranged
var fruit1 = "apple"
var fruit2 = "banana"
var fruit3 = "cherry"
var fruit4 = "orange"
var fruit5 = "grapes"
var fruit6 = "mango"
var fruit7 = "pear"
var fruit8 = "kiwi"
var fruits = [
"apple",
"banana",
"cherry",
"orange",
"grapes",
"mango",
"pear",
"kiwi"]
A storage shelf with numbered spots
var fruits = [];
Why?
You might want to add stuff to it later, one element at a time.
(I will show you soon)
var fruits = ["apple", "banana", "cherry"];
0 1 2
page 128
var myBanana = fruits[1];
var fruits = ["apple", "banana", "cherry"];
0 1 2
page 129
var fruits = ["apple", "banana", "cherry"];
var howMany = fruits.length; // 3
Array.length is a property all arrays have
page 130
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)
foo = 42;
baz = 3.1415;
foo = "Hello";
baz = 'world!';
foo = true;
baz = false;
foo = true;
baz = false;
NEW!
The expandable variable
// Remember your adventure game inventory?
var inventory = ["sword", "axe", "key"];
// Now you have only one variable instead of:
var inventory1 = "sword";
var inventory2 = "axe";
var inventory3 = "key";
var inventory4 = "";
var inventory5 = "";
// Check number of items:
if (inventory.length > 3) alert('too many items');
var fruits = ["cherry", "banana", "apple"];
fruits.length == 3 // true
fruits.sort(); // ["apple", "banana", "cherry"];
//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');
//Specify a position
circles[4] = 'red';
// pop removes the last element
circles.pop();
// shift, removes the first element
circles.shift();
// weird quirk
circles.length --
// remove 1 at position 3
circles.splice(3,1);
/******************************
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']
******************************/
/******************************
Splice can also
Remove multiple items and
Add new items:
******************************/
var pokerHand = ["Q", "Q", "Q", "J", "8"];
var unwanted = pokerHand.splice(3, 2, "A", "A");
/******************************
pokerhand: ["Q", "Q", "Q", 'A', 'A']
unwanted: ['J', '8']
******************************/
even if you don't know how many elements there are
var fruits = ["kiwi", "mango", "orange", "banana", "apple"];
var index = 0;
while (index < fruits.length) {
console.log( fruits[index] );
index++;
}
...as you know
is a compressed form of while
var array = [1,2,3,4];
for ( var i = 0; i < array.length; i++ ) {
//array[i]
}
page 140
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.
// 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]
// 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"
var fruits = ["kiwi", "mango", "orange", "banana"];
fruits.length
// 4 (returns the amount of elements)
fruits.indexOf("kiwi")
/* search for the index of a specific value
0 (If the argument passed in doesn't exist,
-1 is returned. If two exist, the first is returned) */
fruits.reverse()
// reverses the order of the elements
// ["banana", "orange", "mango", "kiwi"]
fruits.sort();
// sorts alphabetically (even numbers are sorted alphabetically)
// ["banana", "kiwi", "mango", "orange"]
fruits.splice(2, 1)
/* starts deleting elements from index 2 (orange)
and deletes one (1) item.
The deleted item(s) is returned as an array */
You can read about all methods here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
combining two arrays
/******************************
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']
******************************/
2# Find the Element By searching for its CSS selector
document.querySelector("#main-menu")
// <nav id="main-menu">...</div>
<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 element that match the argument passed in.
<div id="demo">
<h1>Existing content</h1>
</div>
var div = document.querySelector('#demo');
div.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>
HTML
HTML
Browser output
Browser output
Using innerHTML
By Johan Kohlin