How to implement createuniqueCopy() in actionscript 3?
I came across this thread:
Is开发者_StackOverflow社区 there a function like array_merge in PHP in actionscript 3?
PHP has a built-in function that does this:
array array_merge ( array $array1 [, array $array2 [, array $... ]] )
And seems I need to include as3corelib library in order to use createuniqueCopy
.
How to implement createuniqueCopy
in order to reduce the size of the swf?
I would encourage you to use ArrayUtil as part of the as3core library. The file is only 5kb, and contains only a few functions so is very lightweight. If you import it, Flash is smart enough to only include the files it needs, so it won't bring in all the code from the entire as3core library.
On the other hand, if you really wanted to create your own, do something like:
var a1:Array = ["a", "b", "c"];
var a2:Array = ["b", "j", "e"];
var a3:Array = a1.concat(a2);
a3 = uniqueArray(a3);
trace(a3); // a,b,c,j,e
function uniqueArray(a:Array):Array {
var newA:Array = [];
for (var i:int = 0; i < a.length; i++) {
if(newA.indexOf(a[i]) === -1) newA.push(a[i]);
}
return newA;
}
Edit (question was clarified in comments)
If you are using associative arrays, Adobe recommends using Objects, not Arrays for associative arrays. See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html
Adobe Do not use the Array class to create associative arrays (also called hashes), which are data structures that contain named elements instead of numbered elements. To create associative arrays, use the Object class. Although ActionScript permits you to create associative arrays using the Array class, you cannot use any of the Array class methods or properties with associative arrays.
So, tackle the problem like this:
var a1:Object = {};
var a2:Object = {};
a1["a"] = "the a";
a1["b"] = "the b";
a2["b"] = "the b2";
a2["c"] = "the c";
var a3:Object = uniqueArray(a1, a2);
for each(var i:* in a3) {
trace(i);
}
// outputs [the a, the b, the c]
// 'the b2' is omitted because 'b' key already exists
function uniqueArray(a1:Object, a2:Object):Object {
var newA:Object = {};
for(var i:String in a1) {
newA[i] = a1[i];
}
for(var j:String in a2) {
if(newA[j] === undefined) newA[j] = a2[j];
}
return newA;
}
1) you don't need to use the entire library, just import the arrayUtils class: https://github.com/mikechambers/as3corelib/blob/master/src/com/adobe/utils/ArrayUtil.as
and then use the function: var c:Array = ArrayUtil.createUniqueCopy(a1.concat(a2));
this will exclude duplicates, inorder to have exactly the same values with duplicates just remove:
if(ArrayUtil.arrayContainsValue(newArray, item)){ continue; }
from the createUniqueCopy function
some examples: Cleanly merge two arrays in ActionScript (3.0)?
精彩评论