With variables, you can hold onto one piece of information. If you wanted to keep track of all the items in a shopping cart, you'll have to write code like this:
var mycart0 = 'tomatoes'; var mycart1 = 'milk'; var mycart2 = 'eggs'; var mycart3 = 'potatoes'; ...It could easily get very long (imagine keeping track of 10000 items).
If you have this kind of data structure, you can address them by indexing into the array
alert(mycart[0]); // 'tomatoes' alert(mycart[3]); // 'potatoes'
var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; // an array of strings var mixedBag = [1, 'reed.edu', true, -23.3] // array with different data types var playList = []; // an empty array var setting = [ 'hot', 'cold', 'mild', 'crunchy', ];
var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; alert(days[0]); days[0] = 'Lundi'; // change the value of arrays alert(days[0]); alert( days[1] ); // added white space so easier to read alert( days[2] ); alert( days[3] ); alert( days[6] ); // 'Sun' alert( days[7] ); // ??
days.lengthThis will act like a variable with the length of the array in it and can be used like the following:
var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']; // an array of strings days[days.length -1]; // this will always index into the end of the array. In this particular case // will evaluate to days[6]
Adding items to an array
var myCart = ['tomatoes', 'milk', 'eggs', 'potatoes'];
// adding items to the end of array
myCart[4] = 'banana';
myCart[myCart.length] = 'bread';
// .push() adds one or more items to the end of an array
myCart.push('cheese');
myCart.push('tea', 'pasta', 'ice cream');
//adding item to the beginning of an array
myCart.unshift('yogurt');
var p = [0,2,5,1]; var totalItems = p.push(4,5); // totalItems contains 6 numbers 0,2,5,1,4,5
Deleting items from an array: pop() removes the last item from the array. shift() removes the first item from the array
var pp = [0, 1, 2, 3]; var poppedItem = pp.pop(); // [0, 1, 2] and poppedItem contains 3 var pushedItem = pp.shift(); //[1, 2] and pushedItem contains 0
We've actually been using objects.
document.write('hello'); var p = [1,2,3,4]; p.length;
personalInfo.myAge = 25; personalInfo.myCity = 'Portland'; alert(personalInfo.myStreet(....));
<p id="reed"></p> <script> document.getElementById("reed").innerHTML = "Reed College"; document.getElementById("reed").style.color = "blue"; document.getElementById("reed").style.backgroundColor = "Yellow"; </script> <p class="schools"></p> <p class="schools"></p> <script> var schoolarray = document.getElementsByClassName("schools"); schoolarray[0].innerHTML = "School 0"; schoolarray[1].innerHTML = "School 1"; </script>
var price = 10; // this is a single line of comment /* This is a multiline comment. Author: Jane Smith The code makes your website look great. You use this by ... */