·您当前的位置:首页 > 技术教程 > AS2与AS3技术 >

[AS3]as3数组中找出指定的数组元素

时间:2014-08-09 14:57酷播
[AS3]as3数组中找出指定的数组元素

解决方法:用for语句和break语句就能找到匹配的元素。另外用ArrayUtilities.findMatchIndex(), ArrayUtilities.findLastMatchIndex()和ArrayUtilities.findMatchIndices()方法

代码实现查找功能:

var letters:Array=["a","b","c","d","e"];

var match:String="b"//指定要搜索的内容;

for(var i:int=0;i<letters.length;i++){

if(letters[i]==match){

trace("找到了"+match+"在数组第"+i+"个位置");

break;

}

}

也可以从数组最后一个元素开始查找;

for条件改为for(var i:int=letters.length-1;i>=0;i--)

使用自定义类ArrayUtilites类更简单,它在ascb.util包中,首先导入它:

import ascb.util.ArrayUtilities;

ArrayUtilities类有三个方法来查找匹配的元素findMatchIndex(),findLastMatchIndex(),和findMatchIndices。

用ArrayUtilies.findMatchIndex来实现查找功能:

var letters:Array=["a","b","c","d"];

trace(ArrayUtilities.findMatchIndex(letters,"b"));

显示结果:1

trace(ArrayUtilities.findMatchIndex(letters,"r"));

显示结果:-1

也可以拽定搜索的起始下标作为第三个参数:

var letters:Array=["a","b","c","d"];

trace(ArrayUtilities.findMatchIndex(letters,"d",1))//指定从数组下标为“1”的元素开始搜索

显示结果为:3

如果第三个参数为true,则返回部分匹配的元素:

var words:Array=["bicycle","baseball","mat","board"];

trace(ArrayUtilities.findMatchIndex(words,"s",true));

显示:1

findLastMatchIndex()方法返回最后一个匹配的元素下标

findMatchIndices()方法返回所有匹配的元素下标数组;

var letters:Array=["a","b","c","d","a","b","c","d"];

trace(ArrayUtilities.findMatchIndices(letters,"b"));

//显示结果:1,5

var letters:Array=["bicycle","baseball","mat","board"];

trace(ArrayUtilities.findMatchIndices(letters,"b",true));

//显示结果:0,1,3

热门文章推荐

请稍候...

保利威视云平台-轻松实现点播直播视频应用

酷播云数据统计分析跨平台播放器