原文:https://segmentfault.com/a/1190000007239515
//克隆函数 亲测有效
//不支持 类型
// Symbol
//支持 类型
// Boolean
// Null
// Undefined
// Number
// String
// Array
// Object
// function
//测试
// console.log(g_clone(true));
// console.log(g_clone(false));
// console.log(g_clone(0));
// console.log(g_clone(12));
// console.log(g_clone(''));
// console.log(g_clone('abc'));
// console.log(g_clone(null));
// console.log(g_clone([1,2,3]));
// console.log(g_clone([]));
// console.log(g_clone({name:'zh',age:'18'}));
// console.log(g_clone({}));
// cc.log(g_clone(g_arrayEqual) == g_arrayEqual)
//测试结果
// true
// false
// 0
// 12
// ""
// abc
// null
// (3) [1, 2, 3]
// []
// {name: "zh", age: "18"}
// {}
// false
function clone(obj){
var copy;
switch(typeof obj){
case 'undefined':break;
case 'number':
case 'string':
case 'boolean':copy = obj;break;
case 'function':
//先把函数转成字符串 在把字符串克隆转成函数 cc.log(g_clone(g_arrayEqual) == g_arrayEqual) 结果false
copy = new Function("return " + obj.toString())();
//或者直接返回引用 cc.log(g_clone(g_arrayEqual) == g_arrayEqual) 结果true
//copy = obj;break;
break;
case 'object':
if(obj == null) copy = null;
else if(toString.apply(obj) === '[object Array]')
{
copy = [];
for(var i in obj) copy.push(clone(obj[i]));
}
else
{
copy = {};
for(var j in obj)
copy[j]= clone(obj[j]);
}
}
return copy;
}
window.g_clone = clone
网友评论