CIS 111 Lecture 7: Arrays

34 views3 pages
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;
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

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;

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Questions