Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a C/C++ data structure equivalent in Javascript?

Tags:

c++

javascript

c

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

like image 642
Mark K Avatar asked Jul 23 '26 17:07

Mark K


1 Answers

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';
like image 85
lincolnk Avatar answered Jul 26 '26 06:07

lincolnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!