I have an indexed array full of strings.
I'm generating an integer elsewhere in my code which I want to use to lookup the appropriate index in my_array.PHP Code:my_array = new Array("hello", "dear", "goodbye", "cruel", "world", "never", "noticed");
However, the number I'm passing to the [] access operator could be positive or negative, and it could be more or less than my_array.length
For Example:
So, I need someone to help me with the equation (if possible) that I could use so that if I generate the lookUpIndex out of bounds of the Array, I would be able to "wrap" around the array and get the appropriate element.PHP Code:my_array[lookUpIndex]
my_array[52]
my_array[-2]
my_array[-123]
For example:
The real problem is when you get into negative numbers.PHP Code:var lookUpIndex:int = 10;
trace(my_array[lookUpIndex]);
// output "cruel", also known as my_array[3]
I would like 1 equation that could handle both positives and negatives, instead of having to use a conditional.PHP Code:var lookUpIndex:int = -1;
trace(my_array[lookUpIndex]);
// output "noticed", also known as my_array[my_array.length]
var lookUpIndex:int = -7;
trace(my_array[lookUpIndex]);
// output "hello", also known as my_array[0]
var lookUpIndex:int = -10;
trace(my_array[lookUpIndex]);
// output "world", also known as my_array[4]
Basically, I need someone to fill in the equation below:
NOTE: Using the modulo (%) operator works fine when dealing with positive numbers...PHP Code:var lookUpIndex:int = -128;
var i:int = *some equation involving lookUpIndex*
trace(my_array[i]);
But like I said, I'd like to come up with 1 equation that fits all positive and negative look up number scenarios.PHP Code:var lookUpIndex:int = 128;
var i:int = lookUpIndex % my_array.length;
trace(my_array[i]);
Thanks!




Reply With Quote
