-4

trying to create Create an array containing the names of at least three (3) fast food items and then, using a ‘for’ loop, display the array name, index number, and food item as shown below.

             Fast Foods
             fastFoods[0] is pizza
             fastFoods[1] is burgers
             fastFoods[2] is french fries

I can get the array but not the for to display like this.

Mike Wallace
  • 9
  • 1
  • 2

2 Answers2

4

Iterate over an array with for :

each array has a length property.Array indexing starts from 0 but length property starts count from 1.So in your for loop you have to set a condition which will iterate until the end of array is reached.for loop to iterate over an array has the following structure

   for(i=0;i<array.length;i++){  // in your case it will be fastfood.length
        //access elements here 
    }

++ is an increment operator.It will increase the value of i by one after each iteration.It is equivalent to i=i+1;

and inside for loop you can access the elements using the following structure

arrayName[index];

here arrayName is your array name( in this case fastfood) and index is the current i value; so for your case it will be

fastfood[i]

To create an array with for :

first create a new array called fastfood

var fastfood=new Array()  //or
var fastfood=[]   // [] is a valid array notation

if you are goning to create an array using for loop you have to set a condition about how many elements you want to set in your array.For this case the structure will be

for(i=0;i<n;i++){} // here n is your desired number;

inside the for loop you can have a prompt method .It will allow you to enter a food element after each iteration.Prompt is not a good idea,but i assumed you are new to JS.Here is the structure:

fastfood[i]=prompt('enter food name');
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    Thank you for explaining and not just dumping code. That helps people to learn rather than just providing completed code without explanation to blindly meet some goal. – showdev Feb 05 '15 at 20:17
  • Yes thank you. This helped me understand a bit better what I should be doing. Just starting out with javascript. Trying to get my head around it. – Mike Wallace Feb 05 '15 at 20:39
3
var fastFood = ['pizza', 'burgers', 'french fries'];

for (var i = 0; i < fastFood.length; i++) {
  console.log('fastFood[' + i + '] is ' + fastFood[i]);
}
arnolds
  • 778
  • 6
  • 12