creating an array with a for statement
This question already has an answer here:
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');
var fastFood = ['pizza', 'burgers', 'french fries'];
for (var i = 0; i < fastFood.length; i++) {
console.log('fastFood[' + i + '] is ' + fastFood[i]);
}
链接地址: http://www.djcxy.com/p/24532.html
上一篇: 使用jquery循环浏览jsonp
下一篇: 用for语句创建一个数组