Reputation: 6429
I just want the data in this way:
var _2dimen = {};
_2dimen['window1']['panel1'] = '2010-10-01'
_2dimen['window1']['panel2'] = '2010-10-01'
...
_2dimen['window3']['panel1'] = '2010-10-01'
which window and panel number are dynamic.It means I could using the pattern of : I mean: the variable of window and panel is dynamic create in my situation,the window may be window1 or window2... and panel may be panel2,panel4.
var window = windowNumber, panel= panelNumber;
_2dimen[window][panel] = 'some date here';
How can I struct the code to assign and edit the value?
the code I wrote just what I was thought it maybe,it didn't work!! _2dimen[window] = 'data' work fine and I adding the [panel]
_2dimen[window][panel] = 'data' the firebug prompts me that :
_2dimen[window] is undefined
_2dimen[window][panel] = date;
Thank you very much!
Upvotes: 1
Views: 2374
Reputation: 77420
What some call "associative arrays" in JS are just objects:
var twoD = { window1: {
panel1: '2010-10-01',
panel2: '2010-10-02',
...
},
window3: {
panel1: '2010-12-01',
...
}
};
If you're actually naming the indices things like 'window1' and 'panel2', a better approach would be to use arrays. This way, you can loop over panels and windows, yet still set other properties on the top level object and windows.
var twoD = { windows: [
{ panels: ['2010-10-01', '2010-10-02', ...
...
// window3
{ panels: ['2010-12-01']}
],
foo: 'bar'
};
...
twoD.windows[0].panels[1] // '2010-10-02'
And remember, identifiers can't start with a digit.
If the panels set on windows skip some indices, you can do that, too. Note that you can't set properties of an undefined value. _2dimen[window][panel]={}
fails when _2dimen[window]
is undefined. You need to test & set the element at the major index before accessing an element at a minor index.
function TwoD() {
this.windows = [];
}
TwoD.prototype.window = function(i) {
if (! this.windows[i]) {
this.windows[i] = {panels: []};
}
return this.windows[i];
};
...
var wall = new TwoD();
wall.window(2).panels[1] = '2010-12-02';
This is very close to your current implementation, but has the advantage of allowing iteration over windows & panels when other properties are set.
Upvotes: 4