- Home /
How to get the key from Array value
I got a filled javascript unity array.
var playerInventory = new Array ();
I want to find out which key is used for the value "item_Key". For exampl, the array is filled like this:
[0] item_Apple
[1] item_Key
[2] item_Banana
So the value "item_Banana" uses array key 2. How can I get the key for "item_Key" in my script below?
for (var value : String in playerInventory) {
if(value == "item_Key"){
print(value);
itemKeyNumber = playerInventory[.....] //how?
}
}
Answer by OperationDogBird · Aug 29, 2012 at 06:32 PM
You should switch to List rather than the old, and very very slow, javascript array. List is much faster and has a ton of awesome functionalities. Unlike the builtin arrays which are of fixed size, List is resizable.
Heres an example of usage of List with Transforms.
#pragma strict
import System.Collection.Generic;
public var playerInventory:List.<Transform> = new List.<Transform>();
function Start()
{
playerInventory.Add(someTransform1);
playerInventory.Add(someTransform2);
playerInventory.Add(someTransform3);
var index:int=playerInventory.IndexOf(someTransform2);
Debug.Log("Index Of someTransform2 is "+index);
// Output: "Index Of someTransform2 is 1"
}
There are tons of great methods for list that make working with arrays flexible. Most of the same methods that the javascript array uses are available in the list class.
Here is the reference for List .
if you want to use Array, you can do this to get the index
for(var i:int=0;i<playerInventory.Length;i++)
if(playerInventory[i] == "item_$$anonymous$$ey")index = i;