Arrays
Lesson 17 covers some really interesting stuff!
Methods
A method is nothing more than a function; it's just accessed using dot notation.
.push method
You can add an item to the end of an array using the .push method!
.unshift method
Here, we have an array containing the numbers 100 and 50. But by using the .push method, we have added the number 79 to the end of the array. So when we run it from the Terminal, it will return all three numbers: 100, 50, 79.
You can add an item to the beginning of an array by using the .unshift method.
.pop method
You can also remove items from an array. The .pop method removes the last item of the array. So when you run the program, that last item will no longer be returned, but the next item along will be returned instead.
In this case, the .pop method on line 3 will remove 79 from the end of the array. Line 5 will show us which item has been removed; i.e. 79 will be logged out by line 5. By the time we get to line 6 and log out the full array, the number 79 will be nowhere to be seen! .pop magic!
.shift method
As we saw in the last lesson, the .pop method removes things from the end of an array. The .shift method, on the other hand, removes the first item of an array.
In the example above, 100 will be removed by line 3, logged out by line 5, and nowhere to be seen when line 6 logs out the full array.
Iteration: the forEach method
This method is special because it takes a function as an argument.
Functions
In JavaScript, naming a function is not required. It's only required if you're going to be referencing the function at any given point. If you're simply passing in the function as an argument, there's no need to name it.
.length method
In this example, the .length method will log out the length of the array, which is 3, because there are 3 items in the array.
The Challenge
We had to create a program that added the grades together (i.e. 100 + 50 + 79), divided that total by the number of grades (i.e. 229 / 3) and returned the result (i.e. 76.333...). It looked a little something like this:
No comments:
Post a Comment