PDA

View Full Version : finding the position of an array index


brendanb
07-09-2004, 04:49 PM
i was wondering if you have an array value, can you find what number it is in the array's order. For example,

letters=new Array("a","b","c","d");
cnumber=letters.position["c"]
trace(cnumber);

so that cnumber=2. How would I go about doing something like this?

-Brendan

tg
07-09-2004, 05:50 PM
this code was from our library section. its by Roland Levy.

Array.prototype.getPos = function(item){
for(i=0; i<this.length; ++i) {
if (this[i] == item) { return i; }
}
return null;
};

tg
07-09-2004, 05:51 PM
useage would be:
trace(letters.getPos("c"));

BluegillMedia
03-30-2010, 07:09 PM
This doesn't work for me in CS2, neither did indexOf. I am sure it is easy to just have it tell you what position a string is within an array, but none of these seem to work. Any ideas?

i was wondering if you have an array value, can you find what number it is in the array's order. For example,

letters=new Array("a","b","c","d");
cnumber=letters.position["c"]
trace(cnumber);

so that cnumber=2. How would I go about doing something like this?

-Brendan

CyanBlue
03-30-2010, 07:22 PM
So, you are saying that the above code does not work on CS2/AS2???

What do you get when you create a new FLA, paste the code and test movie???
//
Array.prototype.getPos = function (item)
{
for (i = 0; i < this.length; ++i)
{
if (this[i] == item)
{
return i;
}
}
return null;
};

letters = new Array("a", "b", "c", "d");
trace(letters.getPos("c"));

tacos
03-30-2010, 07:54 PM
Works fine with MX2004, as I guess it would with FlashMX.

BluegillMedia
03-30-2010, 07:55 PM
sorry i meant to say AS2

BluegillMedia
03-30-2010, 07:56 PM
I ended up having to use this (which i found on here, but added the 'whicharray' being passed):


_root.findPos = function(value, whicharray) {
var pos;
for (var i = 0; i < ArrayName.length; i++) {
if (ArrayName[i].toUpperCase() == value.toUpperCase()) {
pos = i;
break;
} else {
pos = false;
}
}
return pos;
}

tacos
03-30-2010, 08:15 PM
MX & MX2004 are only AS2.0. :eek: