简单数组建立:
1 var a = [1,true,"旭","","",""]; 2 var b = [a[0]*2,a[1],a[2]]; 3 for (var i = 0;i< b.length;i++){ 4 alert(b[i]); 5 // alert(a.length); 6 }
数组连接:
1 var a = [0,1,2]; 2 var b = [3,4,5]; 3 var s = a.concat([3,4,5]); 4 for (var i =0;i< s.length;i++){ 5 alert(s[i]);
数组之间连接操作符:
1 var a = [1,2,3]; 2 var s = a.join("+"); 3 alert(s);
数组之间拆除操作符:
1 var a = "1+2+3"; 2 var s =a.split("+"); 3 alert(s);
长度的验证:
1 var a = new Array( ); 2 var b = new Array(10); 3 var c = ["1","2","3"]; 4 var d = new Array("1","2","3"); 5 //c[3]="four"; 6 alert(c.length); 7 alert(c==d);
删除最后一个元素:
1 var a = [1,2,3,"旭"]; 2 var s = a.pop(); 3 alert(s);
添加元素:
1 var a = [1,2]; 2 var s = a.push(3); 3 alert(s);
提示:上面两个保持“先进后出”准则
颠倒数组顺序:
1 var a =[1,2,3]; 2 var s =a.reverse(); 3 alert(s);
移除第一个元素:
1 var a =[1,2,3]; 2 var s1 = a.shift(); 3 var s2 = a.shift(); 4 alert(a.shift()); 5 alert(a.shift()); 6 alert(s1); 7 alert(s2);
头部添加元素:
1 var a = [2,3]; 2 var s = a.unshift(1); 3 alert(a);
返回数组的一部分:
需要解释下,负数表示倒数第几个,-1指最后一个元素
(n,m)返回值是 n到m-1,如a.slice(0,3)返回的值是1,2,3
只有一个值时候,表示从这个位置到结束,如果是负数则最大到此位置
1 var a =[1,2,3,4,5]; 2 var s = a.slice(-2); 3 alert(s);
数组排序:
1 var a = [22,4444,1,333]; 2 var b = ["晨","落","梦","公","子"]; 3 var s = b.sort(); 4 alert(s);
插入,删除或替换元素:
插入(第二个参数为0):
1 var s = a.splice(1,0,"啦"); 2 alert(a); 3 alert(s);
删除(两个参数):
1 var s = a.splice(1,0,"啦"); 2 alert(a); 3 alert(s);
替换(三个参数,且第三个参数不为0):
1 var s = a.splice(1,1,11,22,33,44); 2 alert(s); 3 alert(a);
将数组转换成一个字符串:
1 var a = [1,2,3,4,5]; 2 var s =a.toString(); 3 alert("原始:"+a); 4 alert("结果"+s);
时间: 2024-10-25 05:21:13