ActionScript - indexOf Vector.<Object>?
why does the following indexOf(searchElement:T, fromIndex:int = 0):int
not find the object and return -1
?
var v:Vector.<Obj开发者_如何转开发ect> = new Vector.<Object>();
v.push({name:"Geoffrey", age:32});
trace(v.indexOf({name:"Geoffrey", age:32}));
Simple answer is that Vector.indexOf()
searches by reference. In your code you have created two, completely separate objects; they may look identical to you, but that's because you're a human :)
const v : Vector.<Object> = new Vector.<Object>();
const geoff : Object = { name: "Geoffrey", age: 32 };
v.push(geoff);
const index : uint = v.indexOf(geoff);
trace("Geoff is at index: " + index); // Traces "Geoff is at index: 0".
If you want to find the index of an object based on its properties you will want to use a fori
loop.
const people : Vector.<Object> = new Vector.<Object>();
people.push({ name: "Jonny", age: 28 });
people.push({ name: "Geoffrey", age: 32 });
const needle : String = "Geoffrey";
var index : int = -1;
for (var i : uint = 0; i < people.length; i++) {
if (people[i].name == needle) {
index = i;
break;
}
}
trace(needle + " found at index: " + index);
Because, according to the doc, "the item is compared to the Vector elements using strict equality (===).", and {name:"Geoffrey", age:32} !== {name:"Geoffrey", age:32}
, however this would work:
var v:Vector.<Object> = new Vector.<Object>();
var o:Object = {name:"Geoffrey", age:32};
v.push(o);
trace(v.indexOf(o));
The {}
"object literal" syntax creates a new instance of Object
for each usage. The indexOf()
method searches for the specified instance in the vector, and because you are using the object literal syntax twice, you are effectively creating two objects. The second one is not the same as the first one (which you pushed into the vector) and hence will not be found.
精彩评论