我喜歡用下面的語法檢查,因爲它很容易閱讀,少打字和它在伯仲之間的最快方法:
if ("@style" in item) // do something
要當你不分配一個值返回給該屬性「知道它的名字前手使用attribute
方法:
var attributeName:String = "style";
var attributeWithAtSign:String = "@" + attributeName;
var item:XML = <item style="value"/>;
var itemNoAttribute:XML = <item />;
if (attributeWithAtSign in itemNoAttribute) {
trace("should not be here if attribute is not on the xml");
}
else {
trace(attributeName + " not found in " + itemNoAttribute);
}
if (attributeWithAtSign in item) {
item.attribute(attributeName)[0] = "a new value";
}
以下所有的方法來測試,如果一個屬性存在,從這個疑問句列出的答案雲集灰。由於我在11.7.0.225調試播放器中運行了很多次,右邊的值是使用的方法。左邊的值是運行代碼一百萬次所用的最低時間(以毫秒爲單位)。下面是結果:
807 item.hasOwnProperty("@style")
824 "@style" in item
1756 [email protected][0]
2166 (undefined != [email protected]["style"])
2431 (undefined != item["@style"])
3050 XML(item).attribute("style").length()>0
性能測試代碼:
var item:XML = <item value="value"/>;
var attExists:Boolean;
var million:int = 1000000;
var time:int = getTimer();
for (var j:int;j<million;j++) {
attExists = XML(item).attribute("style").length()>0;
attExists = XML(item).attribute("value").length()>0;
}
var test1:int = getTimer() - time; // 3242 3050 3759 3075
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = "@style" in item;
attExists = "@value" in item;
}
var test2:int = getTimer() - time; // 1089 852 991 824
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = (undefined != [email protected]["style"]);
attExists = (undefined != [email protected]["value"]);
}
var test3:int = getTimer() - time; // 2371 2413 2790 2166
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = (undefined != item["@style"]);
attExists = (undefined != item["@value"]);
}
var test3_1:int = getTimer() - time; // 2662 3287 2941 2431
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = item.hasOwnProperty("@style");
attExists = item.hasOwnProperty("@value");
}
var test4:int = getTimer() - time; // 900 946 960 807
time = getTimer();
for (var j:int=0;j<million;j++) {
attExists = [email protected][0];
attExists = [email protected][0];
}
var test5:int = getTimer() - time; // 1838 1756 1756 1775
檢查我的答案在最後。我相信這就是你一直在尋找的! :) – Rihards 2010-10-25 22:08:48