سؤال

في أكشن 3، هل هناك أي طريقة ملائمة لتحديد ما إذا كان مجموعة النقابي (القاموس) لديه مفتاح معين؟

وأحتاج لأداء منطق إضافية إذا كان مفتاح مفقود. أنا يمكن أن قبض على استثناء undefined property، ولكن أنا على أمل أن يمكن أن يكون منتجع تقريري الأخير.

هل كانت مفيدة؟

المحلول

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

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

وحاول هذا المشغل: "في"

نصائح أخرى

و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 لا تعمل.

والحل أكثر موثوقية وperformant للهو استخدام المساواة التامة للتحقق من غير معرفة.

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