Javascript 三种数组复制方式


 /*
  Array Object
  refer to: http://www.w3schools.com/jsref/jsref_obj_array.asp
 */
  



 //最快的
 直接 = 复制操作是最快的。快一个数量级
 arr = arrCopy

 //1.by slice
 var arr = [1,2,3],copyArr;
 copyArr = arr.slice();

 //2.by concat
 var arr = [1,2,3],copyArr;
 copyArr = arr.concat(); 

 //3.loop
 var arr =[1,2,3],copyArr = []
 for(var i = 0; i = arr.length; i++)
    coypArr[i] = arr[i];

//IE 下 的执行效率为 slice > concat > loop
//Firefox 下执行效率一致 slice = concat = loop
//chrome 下执行效率 concat > slice > loop
//safari 执行效率 slice >~~ concat > loop
  //>~~ 几乎相等
  //>~  相差不大

/*

 总体来说 数组复制 不要选择 loop 进行(除非必要),除chorme下 concat 快于 slice外,其他的全部为 slice最快。
 
*/



/*
 function: concat()
 arguments counts: no limitation.
 arguments: array or string
 syntax: array.concat(string,string....);
         array.concat(string,array....);
 describe: base on current array generate a new array.
           基于当前数组创建新数组
*/
//example:
 var arr = ["black","white","red"], arrCopy;
 arrCopy = arr.concat("green",["array_green","array_red"],"yellow");
//result:
 arrCopy : black,white,red,green,array_green,array_red,yellow

/*
 function: slice()
 arguments counts:1 or 2
 arguments: int (;var)
 syntax: array.slice(start,end);
         array.slice(start);
 describe: return specified range of a string
           返回指定范围的数组
*/
  var arr = ["black","white","red","green"], arrCopy;
  arrCopy = arr.slice(1);
  //if argument is one,will return to the end as default
  //if the range is bigger than the array's maximum length,it will return a string with length of 0,like '' 
  //result: white,red,green;

  arrCopy = arr.slice(1,2);  
  //result:white,red;

 /*
  function: splice()//会影响原始数组
  arguments counts: index,howmany,items....
  syntax: array.splice(index,howmany,item1,.....,itemX)
  describe: splice array; 没有返回值操作当然数组
  reference: http://www.w3schools.com/jsref/jsref_splice.asp
 */
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
 fruits.splice(2,0,"Lemon","Kiwi");
 //result:"Banana", "Orange", "Apple","Lemon","Kiwi","Mango"
 fruits.splice(1,2,"Lemon","Kiwi");
 //result:"Banana","Lemon","Kiwi","Mango"

你可能感兴趣的:(JavaScript)