Mathew Kleppin
JavaScript Anyone?
Iteration
Programs made up of different things
Variables
Statements
Conditionals
Loops
Functions
Classes
npm install connect serve-static//server.js
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);//index.html
<!DOCTYPE html>
<html>
<head>
<title>Leaderboard</title>
</head>
<body>
<script>
//Javascript Here
</script>
</body>
</html>Create a program in the browser that emulates a scoreboard.
Add some useability to your score board.
A very simple sort that goes through each element, finding the max/min, and moving that to a temp element.
var notSorted = [7, 3, 6, 4, 10, 8];We find the highest value, and add it to a new array
var notSorted = [7, 3, 6, 4];
var sorted = [10, 8];Then we do it again: (and again, and again, etc)
var notSorted = [7, 3, 6, 4, 8];
var sorted = [10];What does this look like in code?
var notSorted = [7, 3, 6, 4, 10];
var sorted = [];
function step(){
var index = 0;
var max = notSorted[0];
//checks to see if notSorted[1] exists, and if it is higher the max
if(notSorted[1] && notSorted[1] > max){
max = notSorted[1];
index = 1;
}
if(notSorted[2] && notSorted[2] > max){
max = notSorted[2];
index = 2;
}
if(notSorted[3] && notSorted[3] > max){
max = notSorted[3];
index = 3;
}
if(notSorted[4] && notSorted[4] > max){
max = notSorted[4];
index = 4;
}
sorted.push(max);
//remove the element at a specific index
//the 1 is the number of elements to remove
notSorted.splice(index, 1);
}Lets make this better
var notSorted = [7, 3, 6, 4, 10];
var sorted = [];
function step(){
var index = 0;
var max = notSorted[0];
isMax(1);
isMax(2);
isMax(3);
isMax(4);
function isMax(check){
if(notSorted[check] && notSorted[check] > max){
max = notSorted[check];
index = check;
}
}
sorted.push(max);
notSorted.splice(index, 1);
}If we want to do something over and over again, we can use whats called a do-while loop.
var i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);What happens when we don't incriment i?
var i = 0;
do {
console.log(i);
} while (i < 5);Crash! yay!
Apply this to our code
var notSorted = [ 7, 3, 6, 4, 10 ];
var sorted = [ ];
function step(){
var index = 0;
var max = notSorted[index];
var i = 1;
do {
isMax(i);
i++;
} while (i < notSorted.length);
function isMax(check) {
if (notSorted[check] && notSorted[check] > max) {
max = notSorted[check];
index = check;
}
}
sorted.push(max); //add new element to sorted array
notSorted.splice(index, 1); //remove element from previous array
console.log(sorted);
console.log(notSorted);
}If we want to iterate through our array over and over again, we can use whats called a For loop.
for (var i = 0; i < 10; i++) {
console.log(i);
}To break this down:
We create a variable called i, and set it equal to 0; (var i = 0)
We set a condition, we want to run this while i is less then 10; (i < 10)
Each time we run through the array, we want to incriment i; (i++)
By Mathew Kleppin
First look at iteration