2011-08-28 44 views

回答

4

简单回答是Vector.indexOf()通过参考搜索。在你的代码中,你创建了两个完全独立的对象;他们可能看起来与你,但那是因为你是一个人:)

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".

如果你想找到基于其你将要使用fori循环属性的对象的索引。

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);
+1

诅咒我的人性! :p谢谢你帮我清理这个,jonny。 – TheDarkIn1978

2

因为,根据商务部“的项目相比,使用全等(===)的矢量元素”,并{name:"Geoffrey", age:32} !== {name:"Geoffrey", age:32},但是这会工作:

var v:Vector.<Object> = new Vector.<Object>(); 
var o:Object = {name:"Geoffrey", age:32}; 
v.push(o); 

trace(v.indexOf(o)); 
2

{}“对象常量”语法创建一个新实例的Object对每一种使用indexOf()方法在向量中搜索指定的实例,并且因为您使用对象文字语法两次,所以您正在有效地创建两个对象。第二个和第一个不一样(你把它推入矢量),因此不会被找到。

相关问题