js 數組與運算

JS 數組: Array 類 css

1)初始化:html

 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.spa

2)操做:code

join(parm):htm

將數組轉換成字符串,且在每一個項之間加上咱們傳入的分隔符:rem

 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"]rpc

若是在split()方法中不傳遞參數,則它會將字符串中的每個字符作爲數組中的一項.而後返回數組;it

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;

相關文章
相關標籤/搜索