tags:

views:

147

answers:

3

Lets say I have the following in C

struct address{
   char name;
   int  id; 
   char address;
 };

struct address adrs[40];       //Create arbitrary array of the structure. 40 is example
adrs[0].name = 'a';
id[0]        = 1;
...

What is the equivalent way of defining and creating array of a user defined structure.

Thanks

+2  A: 

Equivalent would be creating an array of associative arrays.

var arr = new Array();
arr[0] = { name: "name 1", id: 100, address: "addr 01" };
arr[1] = { name: "name 2", id: 101, address: "addr 02" };
//...

After this, you will be able to do:

arr[0].name = "new name 1";

Or access element:

if (arr[1].name == "name 2") { // will be true
}

Hope it helps.

Pablo Santa Cruz
A: 
<script type="text/javascript">

    function address() 
    {
       this.name="";
       this.id=0;
       this.address=""
    }
    var addresses = new Array(40);

    addresses[0] = new address();
    addresses[1] = new address();
    .....
    .....
    addresses[0].name = 'a';
    addresses[1].id = 5;


</script>
Robert
you can't call a literal object like a method. `new address()` will not work.
lincolnk
@lincolnk. You are right, Thanks. I fixed it.
Robert
you can't use `name:value` notation like that in a function- that's for literal objects.
lincolnk
On that you are wrong. Try it.
Robert
@Robert no, I'm not. you're defining labels instead of member variables. `var a = new address(); alert (a.id);` shows `undefined`.
lincolnk
@lincoln. You are right. Interesting little thing I stumbled upon. Changing my code.
Robert
@Robert now you are declaring "private" variables which are not accessible from outside the scope of `address`.
lincolnk
+4  A: 

If you're going to have a predefined layout for an object, you'd probably want to use a contructor-style function.

function address() {
    this.name = null;
    this.id = null;
    this.address = null;
}

arrays are not typed and you don't have to specify a length.

var adrs = [];

you can create a new instance of address like so

var item = new address(); // note the "new" keyword here
item.name = 'a';
item.id = 1;
// etc...

then you can push the new item onto the array.

adrs.push(item);

alernatively you can add a new item from the array and then access it by indexer.

// adrs has no items
adrs.push( new address() );
// adrs now has 1 item
adrs[0].name = 'a';

// you can also reference length to get to the last item 
adrs[ adrs.length-1 ].id = '1';
lincolnk
@Mark K the array increments it's counter when you call `push` and are 0-based, so after adding the first item you can access it with `adrs[0]`, the 2nd item would be `adrs[1]`, etc.
lincolnk