Javascript - Loops - FOR in
Ağustos 12, 2012 by Javascript Tutorial
|
|
Article Information
This Javascript Tutorial contains and tries to cover following subjects:
- Brief explanation of For in Javascript
- Example to For in loop in Javascript
Articles tries to provide answer to following questions and issues:
- How to iterate in an array or in a object for all elements with loop in Javascript?
- How to make for each loop in javascript?
- How to make a loop without knowing how many element inside in array?
Articles pre-requisites following information:
- General knowledge of variables in Javascript
- General knowledge of arrays in Javascript
- General knowledge of functions in Javascript
- General knowledge of HTML
Brief explanation of For In.. Loop in Javascript
In this Javascript tutorial, we will try to cover For in Loops subject to understand how to execute some code with iterating in an array for count we do not know.
For In is a loop type in Javascript, and allows to execute code some numbers of times that we need. Difference between FOR and FOR IN lays between the iteration - cycle time. If you recall our article about FOR loop, it used to execute a code certain number of times. Lets assume that we have an array that we do not know how many element inside it. Where we will know, what to add for FOR loop as variable start, and loop end condition? FOR IN loops solves this problem.
FOR IN javascript loop, between the parenthesis creates a variable and uses it to store element of element it is iterating inside. To be more practice, lets inspect syntax of for loop first:
var counter
for(counter in ArrayObject)
{
execute some code...;
}
Above code snippet example demonstrates syntax of FOR IN javascript loop. When above JavaScript loop is executed, javascript goes and checks first index number of array right to the IN. It gets "0", and stores that number in "counter" named variable. You can declare that variable with another times. After storing index number, loop is executed. Next cycle, array index number 1 is stored in counter, and block is executed between curly braces again. Till last index of array object, loop executes itself. If you notice here, FOR IN loop automatically executes till it figures out the last index of array. If we would try this with normal Javascript FOR loop, we would had to provide in condition part, counter is smaller than size of array type way.
For a .NET Developer, this FOR IN javascript loop may be similar to FOR EACH loops of C#. They work a bit similar. FOR IN javascript loops basically is a way to loop through in an array without indicating array size.
Example for a Javascript Array
In following javascript example, we will create use FOR IN.. javascript loop in a HTML page.
HTML result page is shown at the right of pane.
Data Layers
Area: | programming \ languages \ javascript \ \ \ |
Ref: | |
Loc: | articles |
Tags: | javascript |
|