This lab goes through the basics of the JavaScript arrays.
An array keeps values in a sequence. Arrays can change size in run-time. You retrieve an element from an array by position. Use the operator []
to locate an element at the given index.
let a = [ 1, 3, 5, 7, 9 ];
console.log(`The second odd number is ${a[1]}.`);
let empty = [ ]; // empty array
empty[1] // undefined
The length
property refers to the number of elements inside the array.
A common method to iterate an array is to use for
loop. You can read and write elements inside the loop using [ ]
.
let p = [ 2, 3, 5, 7, 11 ]; // small primes
for (let i=0; i<p.length; i++) {
console.log(p[i]);
}
JavaScript arrays are a reference data type. When you assign an array variable to another, both variables refer to the same array object.
let a = [1,3,5];
let b = a;
b[3] = 7; // append 7 to array b, which is the same object as array a
console.log(a);
ES6 has a new control structure for of
to iterate arrays and other iterable objects.
You can use it to read the entries of an array one by one.
This control structure is convenient when you only need to access the content of an array, but not the position.
let p = [ 2, 3, 5, 7, 11 ]; // small primes
for (let x of p) {
console.log(x);
}
It should be noted that there is a similar control for in
in JavaScript. However, it may not work as you would expect. Try change the above example to use for in
.
In case you need read-only access to the entries and their position, use the method .entries()
of Array. The method is an iterable list of tuples [index, value]
.
let num = [ 'zero', 'um', 'dois', 'tres' ]
for (let [idx, s] of num.entries()) {
console.log(`In Portuguese, ${s} means ${idx}.`)
}
Arrays are objects in JavaScript and have some built-in methods. See online reference for a list of all methods. The following shows some common methods.
let A = [2,4];
A.push(6); // A becomes [2,4,6]
A.pop(); // returns 6. A becomes [2,4]
A.unshift(0); // A becomes [0,2,4]
A.shift(); // returns 0
let b = [202,175,3,3];
let s = b.join('.'); // "202.175.3.3"
Arrays are useful to keep some values in order. The following example generates prime numbers less than 200. Is also demonstrates the usage of continue
and loop label to force the next iteration.
Please refer to online help for the detail usage of break
and continue
.
let p = [2, 3, 5, 7];
// give a label to the first for loop
loop1:
for (let k=9; k<200; k+=2) {
loop2:
for (let n of p) {
// if k is divisible by a prime in p, continue onto k+2
if (k % n == 0) continue loop1;
}
// after the above for loop, k is verified as prime
p.push(k);
}
console.log(p);
A recent feature called destructuring assignment makes it convenient to extract values from arrays.
let a, b;
[a, b] = [1,2,3,4,5]; // a is 1, b is 2
[, , a, , b] = [1,2,3,4,5]; // a is 3, b is 5
let rest;
[a, b, ...rest] = [2, 3, 5, 7, 11, 13];
// rest is [5, 7, 11, 13]
The spread syntax ...array
also allows to insert content of one array into another.
let a = [1, 2, 3];
let b = [0, ...a]; // b is [0, 1, 2, 3]
Given an array num
, write a JavaScript program to find the largest number in the array.
Use the following code to test your function.
let num = [32, 15, 20, 41, 2, 39];
// your work here
You can put an array as element inside another array. This is known as nested array, and can represent two dimensional arrays, e.g. a matrix. Given a 2D matrix in the variable mat
, write a JavaScript program to find its inverse. See reference to review the mathematics of inverse of 2x2 matrix.
let mat = [
[ 1, 0 ],
[-1, 3 ]
];
// your work here
Given a constant n
, write a JavaScript program to find the first n
Fibonacci number.
const n = 10;
let fib = [ ];
// your work here
// fib should contain [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The sample answers are available at ex2-2q1.js, ex2-2q2.js and ex2-2q3.js respectively.