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]
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:
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 Connect 4 board. Write some code...