Tôi thích sử dụng cú pháp sau đây để kiểm tra vì nó dễ dàng để đọc, ít đánh máy và nó gần như gắn như là phương pháp nhanh nhất:
if ("@style" in item) // do something
Để gán một giá trị trở lại thuộc tính rằng khi bạn don 't biết tên của nó trước khi tay sử dụng attribute
phương pháp:
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";
}
Tất cả trong những cách sau đây để kiểm tra nếu một thuộc tính tồn tại thu thập được từ các câu trả lời niêm yết trên ques này sự. Vì có quá nhiều nên tôi chạy mỗi trong trình gỡ lỗi 11.7.0.225. Giá trị bên phải là phương thức được sử dụng. Giá trị bên trái là thời gian thấp nhất tính bằng mili giây khi chạy mã một triệu lần. Dưới đây là kết quả:
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
Hiệu suất mã kiểm tra:
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
Nguồn
2013-06-13 12:14:52
Kiểm tra câu trả lời của tôi ở cuối. Tôi tin rằng đó là những gì bạn đang tìm kiếm! :) – Rihards