an01 an01 - 3 months ago 19
Javascript Question

Access an array item in its definition, relative index

I am trying to define this array:

postLists = [
[
[46276,76235,78128],
postLists[0][0].length,
1100
], [
[],
postLists[1][0].length,
0
]
];


However, I get an undefined error for all the
postLists[x][0].length
lines.

How do I access the array being defined from itself? Is there a way to relatively select an item without referencing its entire "path" like you would do with folders?
For example in this case, something like
[0].length
would get
[46276,76235,78128]
's length, or
..[1]
(parent) would select
postLists[1]
.

postLists[x][0]
will hold hundreds of thousands of integers, so performance need to be considered.

postLists[x][1]
is the original length which needs to be accessed every few seconds, because of the size of
postLists[x][0]
, it cannot be accessed on the fly so often without harming performance.

postLists[x][2]
is an index to keep track (and store) the items processed, in
postLists[0][2]
the
1100
is used to skip the 1100 first items which have already been processed.

I am using this in a Greasemonkey script, the reason for the sub-arrays in postLists is that I plan to use the script on multiple tabs running at the same time.

The start of the script is setup like this:

window.onkeydown = function(event) {
if (event.ctrlKey && event.altKey) {
switch(event.keyCode) {
case 49: activeList = postLists[0]; break; // 1
case 50: activeList = postLists[1]; break; // 2
case 51: activeList = postLists[2]; break; // 3
case 52: activeList = postLists[3]; break; // 4

case 70: // F
toggleScript = !toggleScript;
if (toggleScript) {
treatItem();
favObserver.observe(topNotice, {attributes: false, childList: true, characterData: true});
} else
stopObserving(true);
break;
}
}
};


Every functions then use
activeList
to refer the selected sub-array.

Answer

You can utilize assignment, with side-effect of creating additional variable; e.g., tmp, used to assign, re-assign a variable which can change multiple occassions

var tmp, postLists = [
  [
    tmp = [46276, 76235, 78128],
    tmp.length,
    1100
  ],
  [
    tmp = [],
    tmp.length,
    0
  ]
];
delete tmp;
console.log(postLists);