首页 > 编程语言 > 详细

javascript Array类型 方法大全

时间:2015-08-28 00:38:04      阅读:259      评论:0      收藏:0      [点我收藏+]

1,创建数组

1 //第一种是使用Array构造函数
2 var colors = new Array();
3 var colors = new Array(20);  //创建length为20的数组
4 var colors = new Array("red","blue","green");
5 //第二种基本方式是使用数组字面量表示法
6 var colors = ["red","blue","green"];

2,获取数组长度

1 var colors = ["red","blue","green"];
2 console.log(colors.length);   //3

3,检测数组

1 var colors = ["red","blue","green"];
2 var isArray = Array.isArray(colors);  
3 console.log(isArray);        //ture 

 4,转换方法

1 var colors = ["red","blue","green"];
2 console.log( colors );  //red,blue,green
3 console.log( colors.toString );     //red,blue,green
4 console.log( colors.valueOf() );   //red,blue,green
5 console.log( colors.join("&") );    //red&blue&green

  toString()方法会返回由数组中每个值的字符串形式拼接而成的一个以逗号分隔的字符串。

  valueOf()方法返回的还是数组

  join()方法只接受一个参数,即作为分隔符的字符串,然后返回包含所有数组项的字符串。如果不给join()传入任何值,或者给他传入undefined,则使用逗号作为分隔符,IE7及更早的版本会错误的使用字符串undefined作为分隔符。

5,栈方法

1 var colors = ["red","blue","green"];
2 colors.push("black");
3 alert( colors );  //  red,blue,green,black
4 var item = colors.pop(); 
5 alert( item );   //black
6 alert( colors.length );  //3

6,队列方法

 1 var colors = ["red","blue","green"];
 2 var item = colors.shift();  //取地第一项
 3 alert( item );  //red
 4 alert( colors );   //blue,green
 5 
 6 var count = colors.unshift(“red”,"black");  //推入两项
 7 alert( colors );   //red,black,blue,green
 8 
 9 var item = colors.pop();  //取得最后一项
10 alert( item );  //green
11 alert( colors );  //red,black,blue

7,重排序方法

 1 var values = [0,1,5,10,15];
 2 values.reverse();    //反转数组项的顺序
 3 alert(values);   //15,10,5,1,0
 4 
 5 values.sort();  
 6 //sort()方法会调用每个数组项的 toString() 转型方法,然后比较得到的字符串
 7 alert(values);  //0,1,10,15,5
 8 
 9 //降序排序
10 function compare(value1,value2){
11   if(value1 < value2){
12       return 1;  
13   } else if (value1 > value2){
14       return -1;  
15   }else{
16      return 0;
17   }
18 }
19 var values = [0, 1, 5, 10, 15];
20 values.sort(compare);
21 alert(values);  //15,10,5,1,0
22 
23 //更简单的比较函数
24 function compare(values1, values2){
25   return value1 - value2;
26 }

8,操作方法

1 var colors = ["red","blue","green"];
2 var colors2 = colors.concat("yellow", ["black", "brown"]);
3 alert( colors2 );  //red,blue,green,yellow,black
 1 var colors = ["red","blue","green","yellow","black"];
 2 var colors2 = colors.slice(1);
 3 var colors3 = colors.slice(1, 4);
 4 alert(colors2);  //blue,green,yellow,black
 5 alert(colors3);  //blue,green,yellow
 6 
 7 
 8 var colors4 = colors.slice(-2, -1);
 9 var colors5 = colors.slice(3, 4);
10 alert(colors4);  //yellow
11 alert(colors5);  //yellow

 

未完……

 

javascript Array类型 方法大全

原文:http://www.cnblogs.com/AllenChou/p/4764713.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!