Working with array of objects (using JavaScript)

by Jagadish Pulakhandam on 8/26/2012 3:11:14 AM
Rated 0 from 0 votes
Brief: Demonstrates on creating an array which holds multiple objects. Also demonstrates on how to traverse/access each object in the array.
Posted to: Advanced JavaScript Programming/Development tutorials/videos- Object Oriented Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached source code/video demonstrates the following:
  • How to define an array in JavaScript
  • How to store JavaScript objects in an array
  • How to traverse through each object in an array
  • How to access members of object available in an array
Source Code:

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
03.<html>
04.<head>
05.    <title></title>
06.    <script type="text/javascript">
07.        //DEMO: Array of Objects
08. 
09.        var Emp = function (vEname, vSal) {
10.            this.Ename = vEname;
11.            this.Sal = vSal;
12. 
13.            //method as a member
14.            this.getAnnSal = function () {
15.                return this.Sal * 12;
16.            }
17. 
18.        };
19. 
20.        //create array
21.        var aryEmp = [];
22.        //add objects as elements to array
23.        aryEmp[0] = new Emp("Jag", 5400);
24.        aryEmp[1] = new Emp("Chat", 6400);
25.        aryEmp[2] = new Emp("Win", 7400);
26.        aryEmp[3] = new Emp("Dhan", 8400);
27. 
28.        //parse array of objects and call/access respective (member) methods
29.        for (var i = 0; i < aryEmp.length; i++) {
30.            alert(aryEmp[i].Ename + " earns annual salary as " + aryEmp[i].getAnnSal().toString());
31.        }
32. 
33. 
34.    </script>
35.</head>
36.<body>
37. 
38.</body>
39.</html>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following