首页 > 代码库 > 数组复制

数组复制

数组复制:

bad:

function aa(){
    var items = [1,2,3,4,5];
    var len = items.length,
    itemsCopy = [],
    i;
    for (i = 0; i < len; i++) {
       itemsCopy[i] = items[i];
    }
   return itemsCopy;
};
var a=aa();
console.log(a);// [1,2,3,4,5];

good:

function aa(){
 var items = [1,2,3,4,5],itemsCopy;
 itemsCopy = items.slice();
 return itemsCopy;
};
var a=aa();
console.log(a);// [1,2,3,4,5];

 

数组复制