문제

ActionScript 3에서는 연관 배열 (사전)에 특정 키가 있는지 여부를 결정하는 편리한 방법이 있습니까?

키가 없으면 추가 로직을 수행해야합니다. 나는 잡을 수 있었다 undefined property 예외, 그러나 나는 그것이 나의 마지막 수단이 될 수 있기를 바라고 있습니다.

도움이 되었습니까?

해결책

var card:Object = {name:"Tom"};

trace("age" in card);  //  return false 
trace("name" in card);  //  return true

이 연산자를 시도하십시오 : "in"

다른 팁

hasOwnPropery 당신이 그것을 테스트하는 한 가지 방법입니다. 예를 들면 다음과 같습니다.


var dict: Dictionary = new Dictionary();

// this will be false because "foo" doesn't exist
trace(dict.hasOwnProperty("foo"));

// add foo
dict["foo"] = "bar";

// now this will be true because "foo" does exist
trace(dict.hasOwnProperty("foo"));

가장 빠른 방법은 가장 간단 할 수 있습니다.

// creates 2 instances
var obj1:Object = new Object();
var obj2:Object = new Object();

// creates the dictionary
var dict:Dictionary = new Dictionary();

// adding the first object to the dictionary (but not the second one)
dict[obj1] = "added";

// checks whether the keys exist
var test1:Boolean = (dict[obj1] != undefined); 
var test2:Boolean = (dict[obj2] != undefined); 

// outputs the result
trace(test1,test2);

HasownProperty는 인기있는 솔루션 인 것처럼 보이지만 현으로 만 다루고 전화하는 데 비용이 많이들 수 있다는 점을 지적 할 가치가 있습니다.

사전에서 객체를 키로 사용하는 경우 HasownProperty가 작동하지 않습니다.

보다 신뢰할 수 있고 성능이 뛰어난 솔루션은 엄격한 평등을 사용하여 정의되지 않은 것을 확인하는 것입니다.

function exists(key:*):Boolean {
    return dictionary[key] !== undefined;
}

엄격한 평등을 사용하는 것을 잊지 않으면 널 값을 가진 항목이지만 유효한 키는 비어 있습니다.

null == undefined // true
null === undefined // false

그리고 실제로, 언급 된 바와 같이 in 도 잘 작동해야합니다

function exists(key:*):Boolean {
    return key in dictionary;
}

이 시도:

for (var key in myArray) {
    if (key == myKey) trace(myKey+' found. has value: '+myArray['key']);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top