JS 数组 各项操作

构建数组(Array)

var a = new Array(); //创建Array对象

var a = new Array; //创建Array对象

var a = new Array(10); //创建Array对象,并指定数组中项的个数

var a = new Array("a","b","c"); //数组a,b,c

var a = ["a","b","c"]; //数组a,b,c

var a =[["a","b","c"],[1,2,3]]; //多维数组

toStringvalueOf

var a =["a","b","c"];

var s = a.toString();

s =>  a,b,

var s2 = a.valueOf();

s2 =>  a,b,c

 join , split(拼装,分离)

var a =["a","b","c"];

var s = a.join("-");

s  => a-b-c

s.split("-");

=>a,b,c

concat (数据连接)

var a1 = new Array(1,2,3);

var a2 = new Array("a","b","c");

var a3 = a1.concat(a2);

a3 =>1,2,3,a,b,c

splice(删除,替换)

var a1 = new Array(1,2,3,"a","b","c");

var a2 = a1.splice(1,2); //从a3中删除从下标为1开始的2项,返回删除的结果给a4

a1 => 1,a,b,c

a2 => 2,3

var a =["a","d","e"];

var a3 = a.splice(1,0,'b','c'); //在位置1(即d)处删除0个项,并插入['b','c']

a=>a,b,c,d,e

a3=>b,c

a4 =a.splice(3,2,'dd','ee'); //在位置3处删2个项,并插入['dd','ee'],即替换

a4=> dd,ee

a=> a,b,c,dd,ee

pushpop

var a1 = new Array(1,2,3);

var a2 = a1.push(4); //顶部压入4,返回压入的对象

a1=> 1,2,3,4

a2=>4

var a3 = a1.pop(); //顶部弹出顶部第一个对象,返回弹出对象

a1=> 1,2,3

a3=>4

var a4 = a1.pop(3); //指定删除某个元素

a4=> 1,2

shiftunshift

var a = new Array(1,2,3);

var a1 = a.shift(); //删除数组的第一项,将其作为函数返回值

a=> 2,3

a1=>1

var a2 = a.unshift(1); //加入一项放在数组的第一个位置,原来的项分别往下移一个位置

a=>1,2,3

a2 =>undefined

 再看看判断一个对象是否为Array对象的方法(判断是一个对象再判断方法)

isArray: function(object) {

return object != null && typeof object == "object" &&

'splice' in object && 'join' in object;

}

posted @ 2012-11-06 08:49  lcuzhanglei  阅读(168)  评论(0编辑  收藏  举报