Is there an XMLList equivalent to Arr开发者_如何学Cay.indexOf?
For example -
var array:Array = ['one','two'];
trace(array.indexOf('two')); // returns 1, since it's at the second position
trace(array.indexOf('three')); // returns -1, since it isn't found
... right? but what if I've got this -
var xml:XML = <list><item>one</item><item>two</item><list>
var xmlList:XMLList = list.item;
there's got to be an easier way to check to see if one of the nodes in the XMLList has a particular value than looping through all of them, right? something akin to -
xmlList.indexOfChildByNodeValue('two'); // returns 1, because it's the second child
xmlList.indexOfChildByNodeValue('three'); // returns -1, because it doesn't match any children
make sense?
I put together a demo of how you can do it without looping. Though it does call for a little more upfront work. Though it pays off if you are going to be checking values a lot.
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="_init();">
<fx:Declarations>
<fx:XML id="movieList" source="http://www.movies.com/rss-feeds/jen-yamato-reviews-rss" />
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.logging.ILogger;
import mx.logging.Log;
import mx.logging.LogEventLevel;
import mx.logging.targets.TraceTarget;
public static const MOVIE_TITLE:String = "Inception";
private var _logger:ILogger = Log.getLogger("Sandbox");
private function _init() :void
{
var traceTarget:TraceTarget = new TraceTarget();
traceTarget.level = LogEventLevel.ALL;
Log.addTarget(traceTarget);
var xmlList:XMLList = movieList..item;
var firstItem:XML = movieList..item[0];
var firstItemIndex:int = firstItem.childIndex();
_logger.info("First Item Index: " + firstItemIndex);
var item:XML = xmlList.(title == MOVIE_TITLE)[0];
_logger.info("Contains: " + xmlList.contains(item) + " // " + item.childIndex());
var actualIndex:int = (item.childIndex() - firstItemIndex);
_logger.info("Actual Index: " + actualIndex);
_logger.info("Result: " + xmlList[actualIndex]);
}
]]>
</fx:Script>
</s:Application>
The basic idea is that you store the index of the first item
and then subtract that from the childIndex()
of the matched result using E4X search.
I think the only bet is to loop through the XMLList. The other option you have is to use: contains() Though this will only help in your situation if you actually only want to know whether indexOf() == || != -1
.
I am not sure of how the XMLList is actually stored in the underlying C++, but if it truly is just an array, then a linear search O(n) is the best you are going to do.
精彩评论