- Home /
How do I find the position of an element in an array?
Hey guys.
I'm having a bit of trouble with finding the position of a string in an array using JScript. Whats the best way to go about this?
I know what the strings are but I need to know what the positions of them are.
Cheers.
This is a Javascript question, not a Unity one.
The question seems relevant here because javascript or a variation of it is a coding language used in Unity. Not to mention that Unity seems to have its own take on arrays.
Unity uses .NET/$$anonymous$$ono arrays, nothing unique. (Aside from the Array class, which is an implementation that's the same as web Javascript arrays.)
Thanks for clearing that up. $$anonymous$$y main point there was that the question isn't irrelevant as the answer will help other unity users.
The problem is that you could say that about all general program$$anonymous$$g questions, since Unity uses program$$anonymous$$g. But general questions would be better served elsewhere since they aren't specific to Unity; that way we can focus on Unity-only questions here.
Answer by dibonaj · Jul 07, 2011 at 02:29 AM
for(int i = 0; i < array.Length; i++)
{
Debug.Log("The element in index " + i + " is " + array[i];
}
I think that should about do it.
Answer by flaviusxvii · Jul 06, 2011 at 11:04 PM
Loop through the array.
Thats what I'm doing, looping through the array to find the string I want but I need to know the index of that string.
@Tides: if you're already looping, then you have the index. That's what the loop index tells you.
You can also use the FindIndex and/or IndexOf methods of the Array class (.NET arrays, not UnityScript arrays), but those methods are specialized, so manually looping through your array is generally faster.
Answer by DrPunchman · Aug 10, 2018 at 09:27 PM
Here is my example, hope this helps someone: It's a rough snippet of something I'm working on.
public string[][] pass = new string[2][];
// define the array somewhere like:
pass[0] = new string[] { "ant", "bug" };
pass[1] = new string[] { "dog", "boy" };
// check for what's in the list
void checkPassword(string k)
{
int i = 0;
int l = pass[0].Lenth;
for(i=0; i < l; i++) // don't define vars in your for() it's slow
{
if(pass[0][i] == k) { print("index --> " + i); }
}
}