本篇文章为大家展示了怎么在JavaScript中复制数组,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
function copyArray(arr){
var result = [];
for(var i = 0; i < arr.length; i++){
result.push(arr[i]);
}
return result;
}
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]
join
使用该方法的缺点是数组中的项全部变成了字符串形式
function copyArray(arr){
var result = [];
result = arr.join().split(',');
return result;
}
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //['1','2','3']
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //['1','2','3',4]
concat
function copyArray(arr){
var result = [];
result = arr.concat();
return result;
}
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]
slice
function copyArray(arr){
var result = [];
result = arr.slice();
return result;
}
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]
深拷贝
以上方法实现的仅是数组的浅拷贝,如果要实现数组的深拷贝,需要使用递归方法
function copyArray(arr,result){
var result = result || [];
for(var i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
result[i] = [];
copyArray(arr[i],result[i]);
}else{
result[i] = arr[i];
}
}
return result;
}
var obj1=[1,2,[3,4]];
var obj2=copyArray(obj1);
console.log(obj1[2]); //[3,4]
console.log(obj2[2]); //[3,4]
obj2[2].push(5);
console.log(obj1[2]); //[3,4]
console.log(obj2[2]); //[3,4,5]
上述内容就是怎么在JavaScript中复制数组,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注天达云行业资讯频道。