# 超难度问题，实现\$merge方法。

cn00439802 2009-12-17 03:31:48
mootools中有\$merge方法能实现以下效果：
``````
var obj1 = {a: 0, b: 1};
var obj2 = {c: 2, d: 3};
var obj3 = {a: 4, d: 5};
var merged = \$merge(obj1, obj2, obj3); //returns {a: 4, b: 1, c: 2, d: 5}, (obj1, obj2, and obj3 are unaltered)

var nestedObj1 = {a: {b: 1, c: 1}};
var nestedObj2 = {a: {b: 2}};
var nested = \$merge(nestedObj1, nestedObj2); //returns: {a: {b: 2, c: 1}}
``````

...全文
74 7 打赏 收藏 举报

7 条回复

fengsky491 2009-12-17
• 打赏
• 举报

arguments[0] = eavl('{' + tmp.join(',') + '}');

return arguments[0];

``````eval('var t =' + '{' + tmp.join(',') + '}');
return t;``````
fengsky491 2009-12-17
• 打赏
• 举报

``````function merge(){
var target = [];

if(!arguments[0]){
return null;
}
for(var i = 0;i < arguments.length;i++){
for(var p in arguments[i]){
target[p] = arguments[i][p];
}
}

var tmp = [];

for(var p in target){
tmp.push(p + ':' + target[p]);
}

arguments[0] = eavl('{' + tmp.join(',') + '}');

return arguments[0];
}``````

fengsky491 2009-12-17
• 打赏
• 举报

xmliy 2009-12-17
• 打赏
• 举报

``````
function \$merge()
{
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
if ( typeof target === "boolean" )
{
deep = target;
target = arguments[1] || {};
i = 2;
}
if ( typeof target !== "object" && target.toString() != "[object Function]" ) target = {};
if ( length == i )
{
target = this;
--i;
}
for ( ; i < length; i++ )
{
if ( (options = arguments[ i ]) != null )
{
for ( var name in options )
{
var src = target[ name ], copy = options[ name ];
if ( target === copy ) continue;
if ( deep && copy && typeof copy === "object" && !copy.nodeType )
target[ name ] = \$merge( deep, src || ( copy.length != null ? [ ] : { } ), copy );
else if ( copy !== undefined )
target[ name ] = copy;
}
}
}
return target;
};

var obj = \$merge(true, obj1, obj2, obj3, ......);
``````
cn00439802 2009-12-17
• 打赏
• 举报

xmliy 2009-12-17
• 打赏
• 举报

var obj = \$.extend(true, obj1, obj2, obj3,......);
cn00439802 2009-12-17
• 打赏
• 举报

8.7w+

Web 开发 JavaScript

2009-12-17 03:31