views:

41

answers:

2

Alright, I'm taking an array, and making another array from it with the only difference being the indexes are displaced by an arbitrary number determined using two reference points (one in each array). Doing this creates negative indexes, which if it didn't stop the script from working, would be useful. Is there any way to have the second array have the negative indexes and work, or am I going to have to use an all-together different method? I rewrote the code to be a simple case.

var firstArray = {
     field: [ 1, 2, 3, 4, 5],
     referenceIndex : 2
};

var secondArray = {
    referenceIndex: 1,
    offset: 0,
    field : {}
};

// Create secondArray.field by finding the offset.
secondArray.offset = firstArray.referenceIndex - secondArray.referenceIndex;

for (i=0; i < firstArray.field.length; i++){
    alert([i - secondArray.offset, firstArray.field[i]].join(" "));
    secondArray.field[i - secondArray.offset] = firstArray.field[i];  //creates a negative index.
}
A: 

An array can have (in a strict sense) only positive integer as indices. However it is also an object, so it can take any string as a property. So in a sense, it will 'work', but do not trust Array#length to have the right value.

var arr = [1,2,3];
arr.length //3
arr[10] = 10;
arr.length //11
arr["blah"] = 100;
arr.length //still 11
arr[-1] = 200;
arr.length //still 11

I'd also like to point you to this excellent article - http://javascriptweblog.wordpress.com/2010/07/12/understanding-javascript-arrays/

Chetan Sastry
A: 

No you can't have negative indices and have it work properly, however, you possibly could save a number and add it to your index to create a positive value. For example you have indeces -2 through 4. In the array this would be 0 - 6 so you would need to add or subtract 2 to get to the value of the index you want.

qw3n