CIS 111 Lecture 7: Arrays
Arrays (Wk 7)
• Accessing Array Elements
o 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
• Add to end of Array
o []
Let groceries=[“milk”, “eggs”, “frostedflakes”];
Groceries[3]=”spam”;
Console.log(groceries); //[“milk”, “eggs”, “frostedflakes”, “spam”];
//inspect the array in the console
o push()
Let groceries=[“milk”, “eggs”, “frostedflakes”];
Groceries.push(”spam”);
Console.log(groceries); //[“milk”, “eggs”, “frostedflakes”, “spam”];
• Remove from end of 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 front of Array: shift()
Let groceries=[“milk”, “eggs”, “frostedflakes”, “spam”];
Let e;
Document Summary
Arrays (wk 7: accessing array elements, let primes=[2,3,5,7]; Console. log(primes[primes[1]); //7: add to end of array. //inspect the array in the console: push() Console. log(groceries); //[ milk , eggs , frostedflakes , spam ]: remove from end of array: pop() //[ milk , eggs , frostedflakes : remove from front of array: shift() //[ eggs , frostedflakes , spam ]: add to front of array: unshift() //[ milk , eggs , frostedflakes , spam ]: find index of item in array let groceries=[ milk , eggs , frostedflakes , spam ]; let pos=groceries. indexof( spam"); console. log(pos); //3 pos=groceries. indexof( fruitloops"); console. log(pos); //-1, roll a die let rolldie=function(){ return math. floor(math. random()*6)+1; let die1=rolldie(); let die2=rolldie(); let num=die1+die2. Arrays (wk 7) console. log(num): count # of times each # is rolled let rolldice=function(n){ 1st 2 elements not used (rolls of 0 and 1) let arr=[0,0,0,0,0,0,0,0,0,0,0,0,0]; //roll dice n times for(let i=1; i<=n; ++i){ die1=rolldie(); die2=rolldie(); num=die1+die2;