Hi,
ich benötigte für ein Projekt die Möglichkeit, Objekte, Arrays, Strings, etc. zu kopieren. Auch wenn diese Typen-gemischt und verschachtelt sind.
Hier ist meine Umsetzung:
ActionScript:
// Object copy
Object.prototype.copy = function () {
// if this has a length
// it must be an array, for objects have no length
if (this.length != undefined) return this.toArray ();
// this is an object
else {
// create result object holder
var result = {};
// copy all nested objects recursively
for (obj in this) result[obj] = this[obj].copy ();
// return result
return result;
}
};
// String copy
String.prototype.copy = function () {
// return String
return String (this);
};
// Number copy
Number.prototype.copy = function () {
// return Number
return Number (this);
};
// Boolean copy
Boolean.prototype.copy = function () {
// return evaluated boolean
return Boolean (Number (this));
// Comment:
// the Number () process is necessary,
// because if it is not used, it would return true every time
};
// Array convert and copy
// IMPORTANT:
// This method forces an array conversion!
// Even if the contents are not Array-like.
Object.prototype.toArray = function () {
// create result array holder
var result = [];
// count results
var resultCount = 0;
// browse through all nested objects
for (obj in this) {
// convert and copy all nested arrays recursively
if (typeof (this[obj]) == "object" && this[obj].length) result[obj] = this[obj].toArray ();
// convert all other non-arrays
else result[obj] = this[obj].copy ();
// increase result count
resultCount++;
}
// if we don't have any results / nested objects
// include this into an Array
// and return this Array
if (resultCount == 0) return Array (this);
// return result
return result;
};
// hide methods
ASSetPropFlags (Object.prototype, ["copy","toArray"], 1);
ASSetPropFlags (String.prototype, ["copy"], 1);
ASSetPropFlags (Number.prototype, ["copy"], 1);
ASSetPropFlags (Boolean.prototype, ["copy"], 1);
// Test
mixed = {};
mixed.obj1 = {};
mixed.obj1.obj = {};
mixed.obj1.obj.str1 = "Object1/Object/String1";
mixed.obj1.obj.str2 = "Object1/Object/String2";
mixed.obj1.obj.arr = [];
mixed.obj1.obj.arr[0] = ["Object1/Object/Array/0/0:String", 0, false, {str: "Object1/Object/Array/0/3:Object/String"}];
mixed.obj1.obj.arr[1] = ["Object1/Object/Array/1/0:String", 1, true];
mixed.obj1.obj.arr.nonArray = ["Object1/Object/Array/NonArray", 2, true];
mixed.obj2 = {};
mixed.obj2.str1 = "Object2/String1";
mixed.obj2.str2 = "Object2/String2";
mixed.obj2.num = 23;
mixed.bool = false;
mixedCopy = mixed.copy ();
numArray = Number (17).toArray ();
Zum Kommentieren, Kritisieren, Korrigieren und Kopieren freigegeben.
Gruß
Yobert