n4pgamer
n4pgamer

Reputation: 624

AS-3 - How to get min/max INDEX of Array

This is NOT about min/max values!

I use Array with all kinds of indices like 0, 1, 2, 1000, -1, -100. Yes, negative indices (I like this feature and I'm thankful for it.). The problem is I need them to be negative otherwise I would have to move all items. Now I wonder how can I retrieve the min index like -100. Most elements between min and max index would be undefined.

var a: Array = new Array();
a[-100] = "hello";
a.forEach(...); // starts with 0

Is there a simple way to get min index ?

Upvotes: 1

Views: 931

Answers (2)

Guffa
Guffa

Reputation: 700302

No, there is no simple way to get the minimum index of the negative keys. You would have to loop through all the keys, convert them to numbers, and get the lowest.

The reason for that is that you are using the array both as an array and as an object. The array only has items with positive indexes, when you assign anything to it using a negative index, it's instead added as a property to the array object, not as an item in the array.

The forEach method loops through the items in the array, so it will only access the positive indexes. The data that you added using negative indexes are not array items, they are properties of the array object. So, it's not a bug that the forEach method starts from index 0.

If you want to loop through everything that you stored in the array, you can loop through its properties, then you will get both the object properties and array items:

for (i in a) {
  // Here i is the key, and a[i] is the value
}

Upvotes: 2

shennan
shennan

Reputation: 11656

It's true that you can have negative indices in AS3 Arrays. The problem (and it's quite a serious one) is that none of the Array methods recognise the negative indices - they only recognise whole numbers.

For example:

var my_array:Array = new Array();

var my_array[-100] = "hello";

trace(my_array[-100]) // hello
trace(my_array.length) // 0
trace(my_array) // [empty]

So standard iteration through the array can only be done with absolute references to the index. Or by treating the array as an Object when looping:

var lowest:int = -100000 /* some deep number */

for(var i in a){

  if(int(i) < lowest){

    lowest = int(i);

  }
}

Upvotes: 1

Related Questions