先来讲下克隆吧,我们都知道对一个变量进行赋值很简单(a=b),但是这只在简单变量中适用,如果是一个深层次的对象或者数组呢?这时候我们就要用到克隆了,因为如果直接进行赋值的话,当前对象的改变会让赋值对象也跟着改变,因为它们指向同一个地址,举个例子:
var objectA = [1, {a: 1, b: 2}]; var objectB = objectA; objectB[1].a = 2; console.log(objectA[1].a); console.log(objectB[1].a);
这里的打印结果都是2,可见如此是不行的,下面我们递归实现克隆():
isType: function (obj) { // 判断当前值类型 return Object.prototype.toString.call(obj).slice(8, -1); } extend: function (temp, result) { if (this.isType(temp) === ‘Object‘) { result = {}; } else if (this.isType(temp) === ‘Array‘) { result = []; } else { return temp; } for (var key in temp) { if (this.isType(temp[key]) === ‘Object‘ || this.isType(temp[key]) === ‘Array‘) { result[key] = this.digui(temp[key]); } else { result[key] = temp[key]; } } return result; }
此外我们还可在此基础上实现删除对象空值:
digui: function (temp, data) { // 确定result的类型 if (this.isType(temp) == ‘Object‘) { data = {}; } else if (this.isType(temp) == ‘Array‘) { data = []; var index = 0; } else { return temp; } for (var key in temp) { if (this.isType(temp[key]) == ‘Array‘ || this.isType(temp[key]) == ‘Object‘) { if (this.isType(temp) == ‘Array‘) { data[index] = this.digui(temp[key]); index++; } else { data[key] = temp[key]; } } else { if (temp[key] != ‘‘) { if (this.isType(temp) == ‘Array‘) { data[index] = temp[key]; index++; } else { data[key] = temp[key]; } } } } console.log(data); return data; }
有点复杂,但是对递归理解有好处!
原文:https://www.cnblogs.com/lsboom/p/11502547.html