Bjo*_*orn 1 javascript air merge webkit
我正在寻找一种将两个关联数组或对象组合成一个的内置方法.如果有所作为,请在Adobe Air中使用webkit.但基本上我有两个对象或关联数组,如果你将:
var obj1 = { prop1: "something", prop2 "anotherthing" };
var obj2 = { prop3: "somethingelse" };
Run Code Online (Sandbox Code Playgroud)
我想合并它们并创建一个具有上述两个对象的所有组合键和值的对象:
var obj3 = obj1.merge( obj2 ); //something similar to array's concat maybe?
alert(obj3.prop1); //alerts "something"
alert(obj3.prop2); //allerts "anotherthing"
alert(obj3.prop3); //alerts "somethingelse"
Run Code Online (Sandbox Code Playgroud)
任何内置函数执行此操作或我必须手动执行此操作吗?
就像tryptych所说的那样,除了他的示例代码(危险和错误,直到他编辑它).更像下面的东西会更好.
mylib = mylib || {};
//take objects a and b, and return a new merged object o;
mylib.merge = function(a, b) {
var i, o = {};
for(i in a) {
if(a.hasOwnProperty(i)){
o[i]=a[i];
}
}
for(i in b) {
if(b.hasOwnProperty(i)){
o[i]=b[i];
}
}
return o;
}
//take objects a and b, and modify object a to have b's properties
mylib.augment = function(a, b) {
var i;
for(i in b) {
if(b.hasOwnProperty(i)){
a[i]=b[i];
}
}
return a;
}
Run Code Online (Sandbox Code Playgroud)
编辑重新:凶猛.深度复制是一个与此不同的正交函数,但仅适合您,这是我的个人深度复制功能
function clone(o) {
var t,i;
if (o === undefined) {
return undefined;
}
if (o === null) {
return null;
}
if (o instanceof Function) {
return o;
}
if (! (o instanceof Object)) {
return o;
} else {
t = {};
for (i in o) {
/* jslint complains about this, it's correct in this case. I think. */
t[i] = clone(o[i]);
}
return t;
}
}
Run Code Online (Sandbox Code Playgroud)