Arrays
Next to numbers, Booleans, strings, or functions, variables can contain two more things: arrays and objects. Let’s look at arrays first.
An array is a list of items in a specific order. These items can be anything (strings, numbers,…).
You create an array by placing the values between square brackets []
while separating them with commas.
For example, these arrays both contain strings:
catsToDoList = ["Nap", "Snooze", "Eat", "Siesta", "Fight with ball of string", "Knock stuff over", "Doze", "Sleep"]
toDoList = ["Bring cape to drycleaner", "Wash Batmobile", "Pick up Robin from school", "Fight crime"]
But arrays can contain any type of value—even other arrays.
numbersOfTheBeast = [6, 6, 6]
myLotteryNumbers = [1, 2, 3, 4, 5, 6]
theGarage = ["Jobs", "Wozniak", "Some friends", ["desks", "electronics", "TV screens", "soldering iron"], ["Apple I", "US$666.66"]]
You can omit the commas when putting the items on separate lines.
theGarage = [
"Jobs"
"Wozniak"
"Some friends"
[ "desks"
"electronics"
"TV screens"
"soldering iron" ]
[ "Apple I"
"US$666.66" ]
]
You can retrieve values by their position in the array. This position is called their index and uses zero-based numbering: The first item will have index number 0
. (Something common in programming languages.)
print theGarage[0]
» "Jobs"
print theGarage[1]
» "Wozniak"
print theGarage[3]
» ["desks", "electronics", "TV screens", "soldering iron"]
With this index, you can also change the value at a certain position of the array.
theGarage[0] = "Steve Jobs"
print theGarage[0]
» "Steve Jobs"
When you have an existing array…
toDoList = ["Bring cape to drycleaner", "Wash Batmobile", "Pick up Robin from school", "Fight crime"]
…you can add extra items to it afterward with push()
.
toDoList.push "Save Gotham", "Pick up cape from drycleaner"
print toDoList
» ["Bring cape to drycleaner", "Wash Batmobile", "Pick up Robin from school", "Fight crime", "Save Gotham", "Pick up cape from drycleaner"]
And an array’s length
property lets you check how many items it contains.
print catsToDoList.length
» 8
print toDoList.length
» 6
print numbersOfTheBeast.length
» 3
print myLotteryNumbers.length
» 6
print theGarage.length
» 5 # (it contains 3 strings + 2 other arrays)