JavaScript Arrays
Arrays
var myNumArray = [7,3,6,3,1,2]; // Create a new array with values
console.log( myNumArray[0] ); // Access the first value (index 0)
myNumArray[2] = 5 ; // Modify the third value (index 2)
- An array is a collection of values which can be used like variables
- The values can be any data type, you can even have multiple types in the same array
- To access the value in an array, you put the array name followed by the slot position containing the value, where 0 is the first slot
- If you pass an array as a function parameter value, changes made to the array values within the function will remain changed out of the function
Creating Empty Arrays
var myArray = []; // Create a new array with no values
- The values can be added later
Adding Items to Arrays
myArray.push("blue"); // Add the value "blue" to the end of the list
Getting Length of Arrays
var myLength = myArray.length;
- This is useful to know so you don't try to access something outside the bounds of the array
Challenge
Make an array of 10 strings and an array of 5 strings, write code that modifies the first item and displays the last item. Run the code once for each array.
Completed