In the slides above, we learnt the arrays allow us to represent a collection of values as a single value:
var myList = [2,6,5,3,10,-2];
We can inspect the value at a particular position in an array, and overwrite them. Remember that arrays are zero-indexed, meaning we start counting from 0 (e.g. the 1st element of the array is position 0, the 2nd is position 1, and so on)
console.log(myList); // outputs 5 myList = "R"; console.log(myList); // outputs [2,6,5,"R",10,-2]
(This is referred to in the slides) Create an array with the items 1, 2 and 4 in it, assigning it to a variable
myArray, and print it out to the console.
(This is referred to in the slides) Starting with
var nums = [5,6,7,8], use appropriate array-related code to do the following:
For the tasks below, there are a number of array functions which will help you. Suppose
var x = ['a','b','c','d','e']:
x.push('f'): Adds an extra item to the end of your array.
x.concat(['f','g']): Appends ('concatenates') two arrays together, producing a new array. The array
xwill be unaffected.
x.join(", "): Joins the elements of an array into one string, separated by the provided separator. Here we'd obtain
"a, b, c, d, e"
"1, 2, 3".split(", "): The opposite - splitting an string using the provided separator, to produce an array. Here we'd obtain
[1, 2, 3]
x.length: This gives the number of elements in the array, here 5. Note that
lengthis a property of the array and not a function, so use
x.indexOf('c'): Locates the position of an element in the array. This expressions will evaluate to 2 (i.e. the 3rd position).
Write code that does the following:
forloop for printing
Write code that goes through each thing in
items and prints out "I like ....".
forloop for summation
Write a function
sumArray which inputs an array, and outputs the sum of the items in the array. The last line of your code within the function should be
return yourArray, which will cause your function to output this value.
Write a function
arrayEvenLengths which inputs an array of strings, and outputs a new array which tells you whether each string has an even number of letters. For example
arrayEvenLengths(["One", "Two, "Four"]) would output
[false, false, true]. The last line within your function should be
You could always avoid use of a
for loop by using the
map function, as described in the slides.
board contains the current state of a noughts-and-crosses board. The aim of the game is to get a row of three 'X's or three 'O's, either vertically, horizontally or diagonally. Write some code that determines whether
board is a winning game position. For example
[['O','O','O'],['X','-','X'],['X','O','X']] would be a win for 'O'. Your code should return
true if someone has won, and