I want to allocate a 2 D Array in Java Script.
I want do some thing similar to this in JavaScript typedef struct { int itemA, int itemB, string testC }myStruc;
myStruct MyArray [100];
How to do this ?
I want to allocate a 2 D Array in Java Script.
I want do some thing similar to this in JavaScript typedef struct { int itemA, int itemB, string testC }myStruc;
myStruct MyArray [100];
How to do this ?
There are a few ways of creating arrays in Javascript, the method closest to what you want to do should be:
var myArray = new Array("someString1", "someString2", "someString3", ...);
You can replace "someString1"
with actual objects.
You can also use the Array constructor to set up the initial length:
var myArray = new Array(5);
myArray[0] = ...;
myArray[1] = ...;
Arrays in Javascript are pretty loose actually - you don't even need to define the length before you access an element that would normally be outside the bounds of the array.
Take a look at the Mozilla documentation on Arrays.
It sounds like you want properties for an array of objects, but I may be misinterpreting.
You may just need something like...
function Person(first, last) {
this.first = first;
this.last = last;
}
var person = new Person("John", "Dough");
http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm
function Sample(value1, value2) {
this.value1 = value1;
this.value2 = value2;
}
var test = new Array();
test[0] = new Sample("a","aa");
test[1] = new Sample("b","bb");
PS: There are several ways to accomplish this in Java Script.
var arr = []
arr[0] = { "itemA": "A", "itemB": "B", "itemC": "C" }
arr[1] = { "itemA": "A", "itemB": "B", "itemC": "C" }
I think you are trying to apply static language constructs to the dynamic and different world of Javascript. Javascript doesn't really have the notion of arrays in the sense that many languages do.
In Javascript, an array is simpl a special kind of object (itself just a hash) which has a special length property. The integer "indexes" that you see above (ie, the 0 in arr[0]) are just has lookups. The special length property is defined to be one greater than the greatest integer key. In my example above, arr.length is 2. But if I were to assign:
arr[100] = { "itemA": "A", "itemB": "B", "itemC": "C" }
Then arr.length would be 101, even though I've done nothing to assign any of the elements from 2 to 99.
Similarly, we generally don't predefine objects like structs in Javascript, and thus anonymous objects will largely accomplish what you want (or use a documented factory function such as in the example from Ken).
"new Array()" isn't necessary as the concise "var a = [];" syntax is quicker. :)
If you really like to allocate 100 elements array of a particular structure, you can do following:
arr = [];
for (i=0; i<100; i++) {
arr[i] = {itemA: <value>, itemB: <value>, textC: <string>, ... };
}