js 数组与运算

JS 数组: Array 类

1)初始化:

   1:  var aArr = new Array();
   2:   
   3:  var aArr2 = new Array(20);
   4:   
   5:  var aArr3 = new Array("a","b","c");
   6:   
   7:  var aArr4 = ["a","b","c"];

它不像JAVA中的数组,在初始化时必须规定长度;JS中的数组可以随便声明;

但它最多能存放的项数是:4 294 967 295;即42亿;即2的32次方;因为现在普遍是32位的CPU.

2)操作:

join(parm):

将数组转换成字符串,且在每个项之间加上我们传入的分隔符:

   1:  var arr = new Array("a","b","c");
   2:  var str = arr.join(-);//str:a-b-c

逆操作:

String 类的:split(par)方法:var arr = "a-b-c".split("-");//arr :["a","b","c"]

如果在split()方法中不传递参数,则它会将字符串中的每一个字符做为数组中的一项.然后返回数组;

concat(Arr):

连接两个数组,返回新数组;但原数组值不变;

   1:  var arr = ["a","b","c"];
   2:  var cArr = arr.concat("d","e");
   3:  var dArr = arr.concat(new Array("f","g"));

操作完后:

cArr:["a","b","c","d","e"]

dArr:["a","b","c","f","g"]

arr :["a","b","c"]

slice(begin,end):

返回数组中的一部分:从第begin开始,直到end(不包括end,也就是end的前一个)

   1:  var arr = ["a","b","c"];
   2:  var a2 = arr.slice(1,2);//a2 : b
   3:  var a3 = arr.slice(1);//a2:b,c

push(val);

向数组的尾部添加一个项;

var ar2 = (new Array("a","b","c")).push("d");//ar2:a,b,c,d

pop();

删除数组最后一项,并返回它的值:

var val = (new Array("a","b","c").pop();//val : c;array:a,b

shift();

删除数组中的第一项;并返回它的值;

var val = (new Array("a","b","c").shift();//val : a;array : b,c;

unshift(parm);

向数组中的顶部插入一个项;其他的项依次后移;

var arr = new Array("a","b","c");
arr.unshift("0");//arr: 0,a,b,c
splice(parm1,parm2,parm3)

将数组项插入数组中部.

1)删除: 只需要声明两个参数就可以从数组中删除任意多个项;表示为:slice(start,num);它表示从start开始,删除num个元素;

2)插入: 声明三个参数:splice(start,0,parm);它表示从start开始,将参数:parm 插入start后面,如:arr.splice(2,0,"d","e","f");将在位置 2 处插入:d,e,f;

3)替换: 和上面的插入不同,将第二个参数设为1;如:arr.splice(2,1,"d","e");表示删除位置 2 处的项,然后插入 d,e;

posted on 2013-01-22 09:05  838603796  阅读(2987)  评论(0编辑  收藏  举报

导航