CS133JS Beginning Programming: JavaScript
Topics by Week | |
---|---|
1. Intro to JavaScript programming | 6. Arrays |
2. Functions, Operators and Expressions | 7.Objects and Object Constructors |
3. Conditional Statements: if and switch | 8. Web Page I/O |
4. Repetition: while, do while, and for | 9. Review |
5. Midterm Check-Point | 10. Term Project |
11. Final |
IntroductionAnnouncementsQ and AWhat's Due this WeekReviewArray Declaration and InitializationArray OperationsArrays and Loopsfor
loopfor
...of
loop2D ArraysArray Methods (and a Property)Get Array Informationlength
indexOf(...)
Modify Array Elementssplice(...)
SyntaxExamplesconcat(...)
Remove Array Elementspop()
shift()
Add Array Elementspush(...)
unshift(...)
Reference
Registration is open. These are the spring term classes reccomended for Software Dev majors:
CS 233JS Intermediate JavaScript
WR 227 Technical Writing
CS 161N Computer Science 1: C# (.NET)
CS 235IM Mobile App Development with JavaScript
Lab 5: Have you started it? Any questions?
Does anyone have any questions about anything?
Term project proposal: Thursday
Reading quiz: Thursday
Lab 5 beta version: Sunday
xxxxxxxxxx
const myArray = []; // Declaration
xxxxxxxxxx
const starWars = ["Rey", "Finn", "Han Solo"]; // Declaration and Initialization
xxxxxxxxxx
console.log(starWars[0]); // Getting a value
xxxxxxxxxx
starWars[1] = "Poe"; // Setting a value
xxxxxxxxxx
console.log(starWars.length); // Getting the array length
xxxxxxxxxx
starWars[starWars.length] = "Yoda"; // Adding a new element and value
Arrays are not copied by the assignment operator. Only a reference is copied.
xxxxxxxxxx
starWarsAgain = starWars; // starWarsAgain is like an alias for starWars
The for loop is especially suited to working with arrays and the for...of loop is only used with arrays.
for
loopxxxxxxxxxx
for (let i = 0; i < starWars.length; i++)
{
console.log(starWars[i]); // The loop counter is used to index the array
}
for
...of
loopxxxxxxxxxx
for (let character of starWars) {
console.log(character); // No array index is needed
}
Arrays can contain other arrays (nested arrays).
xxxxxxxxxx
// Declare a 2D array with three nested arrays
const myArray = [
[], [], []
];
xxxxxxxxxx
// Initialize a 3 X 3 array
const grid = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "]];
// Put an X in the top-left, then center, then bottom-right squares
grid[0][0] = "X";
grid[1][1] = "X";
grid[2][2] = "X";
In the examples below, assume we have defined the array continents
as shown below.
xxxxxxxxxx
const continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Europe", "Australia"];
length
A property that contains the length of an array.
xxxxxxxxxx
console.log(continents.length);
Use this property when you don't know how many elements are in an array, but need to do some operation that requires knowing that.
Example, swapping values in an array
x
// Exchange the value stored at the end of the array with the one stored at the beginning. (Move Asia to the end of the array and Austrailia to the beginning).
const firstValue = continents[0];
const lastIndex = continents.length -1;
const lastValue = continents[lastIndex];
continents[0] = lastValue;
continents[lastIndex] = firstValue;
The continents array is shown as a table below with the operations that swap the values in the first and last elements shown to the right of the array.
continents index value | operations | |
---|---|---|
0 | "Asia" |
→ → firstValue ← ↓ |
1 | "Africa" | ↑ ↓ | 2 | "North America" | ↑ ↓ | 3 | "South America" | ↑ ↓ | 4 | "Antarctica" | ↑ ↓ | 5 | "Europe" | ↑ ↓ | 6 | Australia" |
→ lastValue ↓ ← ← ← |
indexOf(...)
A method that returns the index of the element containing a specified value.
If the value isn't found, indexOf
will return -1.
xxxxxxxxxx
// This will print 4 to the console
console.log(continents.indexOf("Antarctica"));
Use this method when you need to do an operation on a specific element of the array, but only know the value stored in the element and not the index of the element. For example:
x
// Change the name of South America to américa del Sur
const index = continents.indexOf("South America");
continents[index] = "américa del Sur";
splice(...)
The splice() method can be used to insert, remove, or replace elements anywhere in an array. It returns the removed elements.
Insertion: When a new element is inserted, all the elements at higher numbered indices are shifted even higher and the array grows.
Removal: When an element is removed, the elements at higher indices are shifted to lower indices and the array shrinks.
Replacement: When an element is replaced it is essentially the same as assigning a new value to the element and the array stays the same size.
array.splice
(index, numberToDelete, newValue1, ....., newValueN)
xxxxxxxxxx
continents.splice(3, 0, "Atlantis"); // Insert Atlantis at index 3
continents.splice(3, 1); // remove Atlantis
continents.splice(2, 2, "Americas"); // Remove N. and S. America, replace with Americas
concat(...)
Join two arrays.
xxxxxxxxxx
const tooks = ["Merry", "Pippin"];
const bagginses = ["Bilbo", "Frodo"];
const hobbits = tooks.concat(bagginses);
Copy an array. This kind of copy is called a deep copy. because it copies all the elements in the array instead of just copying references.
xxxxxxxxxx
const hobbitsCopy = [].concat(hobbits);
pop()
Removes the last element from an array and returns it.
xxxxxxxxxx
const continent = continents.pop(); // removes Austrailia
shift()
Removes the first element from an array and returns it.
xxxxxxxxxx
const continent = continents.shift(); // removes the first element, Asia
push(...)
Adds an element to the end of an array and returns the length of the new array.
xxxxxxxxxx
const arrayLength = continents.push("Austrailia"); // adds Austrailia at index = length
unshift(...)
Adds an element to the beginning of an array and returns the length of the new array.
xxxxxxxxxx
const arrayLength = continents.unshift("Asia"); // adds Asia at index 0
JavaScript Array Reference on W3Schools
JavaScript Reference: Array on MDN
Beginning JavaScript Lecture Notes by Brian Bird 2018, revised are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.