5原生JSパッケージ深浅クローン
1629 ワード
```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);
```