Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Practice Basic Arrays in JavaScript!
You have completed Practice Basic Arrays in JavaScript!
Preview
Use a for loop to both build an array and iterate through every element in an array.
For Loop Refresher
If you need some help remembering how for loops work check out the For Loops video.
Code for completed solution
/* 1. Create a function named createRandomList that
uses a for loop to create an array containing 10 random
numbers from 1 to 100 (use the supplied function above
to generate the numbers). The function should return that array. */
function createRandomList() {
let randomList = [];
for (let i=0; i<10; i++) {
randomList.push(random100());
}
return randomList
};
/* 2. Call the createRandomList() function and store
the results in a variable named myRandomList. */
let myRandomList = createRandomList();
console.log(myRandomList);
/* 3. Use a for loop to access each element in the loop. Each
time through the loop log a message to the console that looks something like this:
Item 0 in the array is 48
When you're done you should have output 10 lines to the console -- one for each element.
*/
for (let i=0; i < myRandomList.length; i++) {
console.log('Item ' + i + ' in the array is ' + myRandomList[i]);
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Then you had to call that function
to create an array, then use a for
0:00
loop to access each item in that array.
0:00
Now, we provided the function for
the random number generator.
0:04
If you want to brush up on
the Math.random function,
0:09
check out the teacher's notes for links.
0:11
Let's start by creating
the shell of the function, and
0:14
we'll name that function createRandomList.
0:19
I'll type function createRandomList,
a set of parentheses, and a set of braces.
0:22
Now I'll start by creating an empty
array to hold the random numbers.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up