Searching in Array using Array.indexOf() function is very easy
. For example,
var toys:Array = new Array();
toys.push("ball");
toys.push("bat");
toys.push("glows");
toys.push("pads");
toys.push(23);
toys.push(14);
var searchIndex:int = toys.indexOf(“ball”);
if(searchIndex == -1)
{
trace(“No! how can it be there”);
}
else
{
trace(“Yup! it’s there”); //output will be from here
}
So, it works fine when the value inside the indexed array is primitive – i.e. Number, String, Boolean etc. BUT it will not work when array contains objects of type Object. For example,
var toys:Array = new Array();
toys.push({name:"ball", count:2});
toys.push({name:"bat", count:2});
toys.push({name:"glows", count:2});
toys.push({name:"pads", count:2});
toys.push({name:"runs", count:200});
toys.push({name:"wickets", count:2});
var searchIndex:int = toys.indexOf({name:”ball”, count:2});
if(searchIndex == -1)
{
trace(“No! how can it be there”); //output will always be from here if you search an object
}
else
{
trace(“Yup! it’s there”);
}
So, that’s the case for objects. In the syntax of Array.indexOf(itemToSearch:*, fromIndex:int = 0), we notice that the first argument is * data type – i.e. it can be any data type, BUT it’s not working for Object. Would any one have lights on this?
Posted by My Poker Blog on May 17, 2009 at 7:19 pm
New to the blog and wanted to say great blog so far and I am looking forward to reading more and posting some comments of my own. Check my blog if you want, I log all my Poker Session there. Got feedback, post a comment
Posted by Tommyka on October 1, 2009 at 10:37 pm
hey, just came across you blog looks good.
the reason
var searchIndex:int = toys.indexOf({name:”ball”, count:2});
dossent work is becourse object are handled as instances, so if you keep another reference to the object you will get the right result.
here is a little example
var sp1:Sprite = new Sprite();
var sp2:Sprite = new Sprite();
var sp3:Sprite = new Sprite();
var arr:Array = [sp1, sp2, sp3];
trace(arr.indexOf(sp2));
her i have a referance to my sprites so i can check with the same instance.