www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript for...in Loop Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49
for...in is yet another looping construct in JavaScript. The reason we deferred the discussion of this looping construct is very obvious. This looping construct is a very special one to use with arrays and objects, and we think now is the good time to discuss this looping construct as we are now familiar with the JavaScript arrays and objects.

The for...in statement is used to loop or iterate through the elements of an array or through the properties of an object.

The syntax for writing a for...in Loop follows:

for (variable in object)
{
// code to manipulate object properties or array elements
}


The following code example would help us make the concept clearer:

var element;
var students = new Array()
students[0] = "Danial";
students[1] = "Jacob";
students[2] = "Adam"

for (element in students)
{
document.write(students[element] +"") ;
}

The above code creates an array named students with three elements then its uses the for...in loop to iterate through the elements of the array.

In the same way we can use the for...in looping construct to iterate through the distinct properties of an object. Code example follows:

<script type="text/JavaScript">

function student(firstname, age, course)
{
this.firstname=firstname;
this.age=age;
this.course=course;
}

objStudent = new student("Adam", 15, "Web Programming");

for (var prop in objStudent) {
document.write(objStudent[prop] + "</br>");
}
</script>

The output of the above code would be as follows:

Adam
15
Web Programming

Next >>> Lesson No. 22: JavaScript Alert Box







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.