<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var stu1 = {
sname:"ssr",
sage:1,
friends:["s1","s2","s3"]
};
function clone(obj) { //浅克隆(拷贝) 不对引用类型对象复制,例如:数组 数组的话,会直接给地址,也就是两个数组名,一个地址
var newobj = new Object();
for(var key in obj){
newobj[key] = obj[key];
}
return newobj;
}
var clone_stu1 = clone(stu1);
console.dir(clone_stu1);
console.log(clone_stu1 == stu1); //false
console.log(clone_stu1.friends);
console.log(clone_stu1.friends == stu1.friends); //true 浅克隆的表现
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var stu1 = {
sname:"ssr",
sage:1,
friends:["s1","s2","s3"]
};
function isArray(o){
return Object.prototype.toString.call(o)=='[object Array]';
}
function clone(obj) { //深克隆 注意数组的克隆(for)
var newobj = new Object();
for(var key in obj){
if(typeof obj[key] != "object"){
newobj[key] = obj[key];
}
else{
if(isArray(obj[key])==true){
newobj[key] = [];
for(var i=0;i<obj[key].length;i++){
newobj[key][i] = obj[key][i];
}
}
else
newobj[key] = clone(obj[key]);
}
}
return newobj;
}
var clone_stu1 = clone(stu1);
console.dir(clone_stu1);
console.log(clone_stu1 == stu1); //false
console.log(stu1.friends);
console.log(clone_stu1.friends);
console.log(clone_stu1.friends == stu1.friends); //false 深克隆的表现
</script>
</body>
</html>
判断数组参考链接:http://www.jb51.net/article/79939.htm