ActionScript 3 AS3:在数组中搜索
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ActionScript 3 AS3:在数组中搜索相关的知识,希望对你有一定的参考价值。
package com.blogspot.flanture.arrays
{
// search Array as3 functions
// author: http://flanture.blogspot.com
// contact: flanture@gmail.com
// January 2010
import flash.display.Sprite;
public class SearchArray extends Sprite {
public function SearchArray() {
// example usage
var a:Array = [1,2,3,5,3];
var b:Array = [2,4,6,8];
search(6, b);
trace("a combined with b: "+combine(a,b));
trace("6 exists in b? "+searchB(6,b));
trace("number of 3 in a? "+searchCount(3,a));
trace("intersection of a and b: "+iSection(a,b));
trace("shuffled b: "+shuffle(b));
}
// function search finds element in array and displays result
public static function search(word:Object, arr:Array):void {
var exists:Boolean = false;
for(var i:uint=0; i < arr.length; i++){
if(arr[i]==word){
trace("Element exist on position "+i);
exists = true;
}
}
if(!(exists)){
trace("Element doesn't exist in array.");
}
}
// function searchB finds element in array and returns Boolean value
public static function searchB(word:Object, arr:Array):Boolean {
var exists:Boolean = false;
for(var i:uint=0; i < arr.length; i++) {
if(arr[i]==word){
exists = true;
}
}
return exists;
}
// function searchCount returns number of apperances of element in array
public static function searchCount(word:Object, arr:Array):uint {
var counter:uint = 0;
for(var i:uint=0; i < arr.length; i++) {
if(arr[i]==word){
counter+=1;
}
}
return counter;
}
// function iSection returns intersection array of two arrays
public static function iSection(arr1:Array, arr2:Array):Array {
var arr3:Array = new Array();
var count:uint = 0;
for(var i:uint=0; i < arr1.length; i++){
for(var j:uint=0; j < arr2.length; j++){
if(arr1[i]==arr2[j]){
arr3[count] = arr1[i];
count+=1;
}
}
}
return arr3;
}
// function shuffle simply shuffles given array elements
public static function shuffle(b:Array):Array {
var temp:Array = new Array();
var templen:uint;
var take:uint;
while (b.length > 0) {
take = Math.floor(Math.random()*b.length);
templen = temp.push(b[take]);
b.splice(take,1);
}
return temp;
}
// function combine returns union of two arrays
public static function combine(ar1:Array, ar2:Array):Array {
var rAr:Array = new Array();
var i:uint = 0;
var j:uint = 0;
while((i < ar1.length) || (j < ar2.length)) {
if(i < ar1.length){
rAr.push(ar1[i]);
i+=1;
}
if(j < ar2.length){
rAr.push(ar2[j]);
j+=1;
}
}
return rAr;
}
}
}
以上是关于ActionScript 3 AS3:在数组中搜索的主要内容,如果未能解决你的问题,请参考以下文章
ActionScript 3 在AS3中排序多维数组(按字母顺序)