由于数组在js中是复合类型,直接赋值是用传址方式而不是传值方式,所以直接赋值的话,并不会“复制”一份独立的数组出来,而是将原数组的地址,传给了另一个变量而已。所以,我们需要用特殊的方式来复制数组,将数组中的元素,一个一个提取出来赋值。
=====================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿当制作</title>
</head>
<body>
<script type="text/javascript">
var a = [1,2,3];
var b = a;
b[0] = 4;
var c = [1,2,3];
var d = [];
for(var p in c){
d[p] = c[p];
}
d[0] = 4;
alert("a:"+a[0]+","+a[1]+","+a[2]+"\n"+"b:"+b[0]+","+b[1]+","+b[2]+"\n"+"c:"+c[0]+","+c[1]+","+c[2]+"\n"+"d:"+d[0]+","+d[1]+","+d[2]);
</script>
</body>
</html>
====================================
其实除了这种方法,还有一种更简单的方法,就是调用数组的slice()方法。slice()方法是截取当前的数组,返回一个“新”数组。如果slice()方法不传参,就会将数组不做截取的返回一个“新”数组回去。
====================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿当制作</title>
</head>
<body>
<script type="text/javascript">
var a = [1,2,3];
var b = a.slice();
b[0] = 4;
alert("a:"+a[0]+","+a[1]+","+a[2]+"\nb:"+b[0]+","+b[1]+","+b[2]);
</script>
</body>
</html>