<
start
>
clear
copy to:
0
insert
save as:
new page
new last
delete
Data Structures: Lists, Dictionaries, and Strings
Variables hold individual values, but sometimes we want to easily deal with a bunch of related values, and pass them around as a unit. The most common ways to do that are with Lists, Dictionaries, and Strings A List is just a list of values. They are created by putting the list in angle brackets, like this: myList = [1, 2, 3] myList You can get individual elements of a list by asking for them by index: myList[1] As you can see, the first element of a list is always at position 0: myList[0] Asking for a list element out of bounds always returns undefined myList[-1] myList[4] myList['a'] The length of a list is always given by its 'length' property myList.length So the last element is always given by its length - 1 myList[myList.length - 1]
What goes inside the square brackets to index a list is any expression at all i = 1 myList[i + 1] Which makes it easy to (for example) perform computations on a list sum = 0 for(var i = 0; i < myList.length; i++) { sum = sum + myList[i] } sum You can assign to any element of a list: myList[2] = 4 myList or add elements to the end with push() myList.push(5) myList We can take elements off the end with pop(), which returns the element popped: myList.pop() myList