Arrays!
Goals:
- Learn about the JavaScript array object
- Use arrays in for loops and as arguments to
randomto write more concise and interesting programs
Coding Snippets:
- Create an array by putting a comma-delimited list of values and/or variables inside a pair of brackets.
- The for loop to the left repeats three times, once for each element in the array.
- In each iteration of the loop, the variable
rrepresents a different turtle.
Math and Computer Concepts:
- You can think of "array" as a fancy word for "ordered list".
- We have been using arrays since the For Loops! lesson:
[1..4]is a CoffeeScript shortcut to create the array[1,2,3,4]. - Arrays can hold any type of data, including numbers, strings, objects (such as Turtles), and even other arrays.
- The
randomfunction accepts array arguments. For example,random([-90..90])returns a value between -90 and 90.
Activities:
Use variables, arrays, and loops to complete the following tasks using as few lines of code as possible. Save your scripts in a folder called Arrays.
- Code a version of Starburst that randomly selects the color of each burst from an array of colors that go well together, (i.e., a "color family" such as
reds = [indianred, crimson, red, darkred, firebrick]). - Starbursts: write a script to generate multiple randomly-placed and randomly-sized starbursts. Each one should randomly choose colors from a single, randomly-chosen family of colors, e.g.,
colors = random([reds, blues, greens]). StarburstSplat: use a nested loop to draw multiple startbursts in the same location. The outer loop should pick the location and set the max burst length as it iterates over the array of colors; the inner loop should draw each single-colored starburst.
-
TurtleVersusFrog: Code a race between a turtle and a frog (use the wearfunction and images). The turtle should move forward every turn, either 1, 2, or 3 units. 80% of the time, the frog should not move. However, the other 20% of the time, it should move forward a larger amount. To simulate this, create an array with 8 zeroes and two values greater than 3. Use the random function in each iteration to randomly select from this array, using the resulting value as the frog's distance.



