日期:2014-05-16  浏览次数:20380 次

javascript数组方法学习总结
join()


js代码

  
 <strong>var colors = ["red", "blue", "green"];    
        
    alert(colors); // red,blue,green    
        
    colors2 = colors.join("-");    
        
    alert(colors2);//red-blue-green </strong>
 




push()


hush()可以接收任意数量的参数,把它们加到数组中,返回修改后的数组长度。
js代码

   
var colors = ["red", "blue", "green"];  
      
    var length = colors.push("white");  
      
    alert(colors); //red,blue,green,white  
    alert(length); //4  


push把参数添加到数组colors的末尾,并返回来数组长度4


pop()


从数组末尾移除最后一项,减少数组的长度。返回移除的项。
js代码

   
var colors = ["red", "blue", "green"];  
      
    var color = colors.pop();  
      
    alert(colors);  //red,blue  
    alert(color);   //green  




shift()

shift()方法可以移除数组中第一个项, 并返回该项。


unshift()


它能在数组前端添加任意个项,返回新数组的长度。


reverse()


把数组的项颠倒。


sort()


对数组进行分类。


concat()


合并数组。


js代码

   
var colors = ["red", "blue", "green"];  
      
    var colors2 = colors.concat(["white", "2"]);  
      
    alert(colors2);     //red,blue,green,white,2  

slice()


可以把一个数组中的一或多项分割开来,创建一个新的数组。
js代码

   
var colors = ["red", "blue", "green"];  
      
    var colors2 = colors.slice(1);  
    var colors3 = colors.slice(0,1);  
      
    alert(colors2);  //blue,green  
    alert(colors3);  //red  

当进入一个参数的时候表示从数组项的哪开始分割,两个参数时是指定范围。


splice()


splice用途比较多,

删除: splice(0,2) 0第一项的位置,2要删除的项数。

插入: splice(2,0,"red","green") 2项的位置,0要删除的项数,插入"red","green"

替换: splice(2,1,"red","green")  把第2位置的一项删除,插入"red","green"


这个方法会返回一个修改后的数组。