首页 > 代码库 > Javascript对象拷贝(clone)
Javascript对象拷贝(clone)
Javascript对象拷贝(clone),希望大家给点建议
?1. [代码]方法代码
function cp(source, target) {
function isBaseType(v) {
var type = typeof v;
var basetype = {
"string": true,
"number": true,
"boolean": true,
"function": true,
"undefined": true
};
return basetype[type] || v === null;
}
function createClone(v) {
var clone = [];
if (!(v instanceof Array)) {
clone = {};
}
return clone;
}
function createCloneFn(fn) {
var fncode = fn.toString();
var regex_params = /^function\s+?(\()([\s\S]*?)(\))/;
var params = [];
var params_index = 2;
var result = fncode.match(regex_params);
if (result) {
var param_code = result[params_index];
if (param_code) {
params = param_code.split(",")
}
}
var fncode = fncode.replace(regex_params, "").replace(/^\s*?\{|\}\s*?$/g,"");
fncode += " console.log(‘clone‘)";
params.push(fncode);
return Function.apply(null, params); ;
}http://www.huiyi8.com/guoqi/?
function createVal(v)
{国旗图标
var val = v;
if( typeof v =="function" )
{
val = createCloneFn(v);
}
return val ;
}
if (source instanceof Function) {
target = createCloneFn(source);
} else if (source instanceof Array) {
if (target instanceof Array) {
var source_size = source.length;
for (var index = 0; index < source_size; index++) {
var item = source[index];
if (!isBaseType(item)) {
var clone_array = createClone(item);
target.push(clone_array);
arguments.callee(item, clone_array);
}
//基础类型
else {
target.push( createVal(item));
}
}
} else {
//console.log("数组拷贝不成立");
}
} else if (typeof source == "object") {
if (!isBaseType(target))
for (var attrname in source) {
var val = source[attrname];
//是否为基础类型
if (!isBaseType(val)) {
var clone_obj = createClone(val);
target[attrname] = clone_obj;
arguments.callee(val, clone_obj);
} else {
target[attrname] = createVal(val);
}
}
}
return target;
}
2. [代码]测试代码
var target = [];
var source = [
[{
a: {
"show": function() {
alert(1)
}
}
}]
];
target =cp(source, target);
?