javascriptコピー
1300 ワード
typeof obj === ("number" || "string" || "boolean")
はtypeof obj === "number"
に相当し、||
の短絡原理に関連しているので、("number" || "string" || "boolean")
は("number")
に相当する.
.function cloneObject(src) {
var result = {};
for (var i in src) {
var type = typeof src[i];
if (type === 'number' || type === 'string' || type === 'boolean') {
result[i] = src[i];
} else {
result[i] = cloneObject(src[i]);
}
}
return result;
}
// :
var srcObj = {
a: 1,
b: {
b1: ["hello", "hi"],
b2: "JavaScript"
}
};
var abObj = srcObj; //
var tarObj = cloneObject(srcObj);//
srcObj.a = 2;
srcObj.b.b1[0] = "hi";
console.log(abObj.a);// 2
// , !!!
console.log(abObj.b.b1[0]);// "hi"
console.log(tarObj.a); // 1
console.log(tarObj.b.b1[0]); // "hello"