标签:argument prot ast 执行 javascrip isarray clone array else
```javascript:run
function deepOrShallowClone() {
var target = null;
var arguments0 = arguments[0];
var lastArguments = arguments[arguments.length - 1];
//首次执行arguments.length为2,后来递归执行arguments.length为3
if (arguments0 === true) {
if ({}.toString.call(lastArguments) === "[object Array]") {
//{}.toString.call也可以用Object.prototype.toString.call代替
target = [];
}
if ({}.toString.call(lastArguments) === "[object Object]") {
target = {};
}
for (var key in lastArguments) {
var value = lastArguments[key];
var isArray = {}.toString.call(value) === "[object Array]";
var isObject = {}.toString.call(value) === "[object Object]";
if (isArray || isObject) {
if (isArray) {
var clone = [];
}
if (isObject) {
var clone = {};
}
console.log("我是深克隆,将通过下面的递归,再次路过这里");
target[key] = deepOrShallowClone(true, clone, value);
} else {
target[key] = value;
}
}
} else if (arguments0 === false) {
target = arguments[1];
} else {
target = arguments0;
}
return target;
}
var beforeClone = {a: 1, b: [2, {c: 3, d: {e: 4, f: [5, {g: 6}]}}]};
var afterShallowClone1 = deepOrShallowClone(beforeClone);
var afterShallowClone2 = deepOrShallowClone(false, beforeClone);
var afterDeepClone = deepOrShallowClone(true, beforeClone);
console.log(afterShallowClone1);
console.log(afterShallowClone2);
console.log(afterDeepClone);
```
标签:argument prot ast 执行 javascrip isarray clone array else
原文地址:https://www.cnblogs.com/gushixianqiancheng/p/10962894.html