数组方法

1、array.concat() (合并数组)

1 var a = ['a', 'b', 'c'];
2 var b = ['x', 'y', 'z'];
3 var c = a.concat(b, true);   //c==> ['a', 'b', 'c', 'x', 'y', 'z', true]

 

2、array.join()(把数组转换成字符串,默认是join(','))

1 var a = ['a', 'b', 'c'];
2 a.push('d');
3 var c = a.join('');         //c==> abcd

 

3、array.pop()(移除数组中的最后一个项,并返回该项)

1 var a = ['a', 'b', 'c'];
2 var c = a.pop();          //a==> ['a','b']    //c==>'c'

 

4、array.push()(将一个或多个参数插入到数组尾部,并返回这个数组的新长度)

1 var a = ['a', 'b', 'c'];
2 var b = ['x', 'y', 'z'];
3 var c = a.push(b, true);   //a==> ['a','b','c',['x', 'y', 'z'], true]     //c==>5

 

5、array.shift()(移除数组中的第一个,并返回该)

1 var a = ['a', 'b', 'c'];
2 var c = a.shift();         //a==> ['b','c'] //c==>'a'

 

6array.unshift()(将一个或多个参数插入到数组头部,并返回这个数组的新长度)

1 var a = ['a', 'b', 'c'];
2 var r = a.unshift('x','y');  //a==> ['x','y','a','b','c', true]   //c==>5

 

 

7、array.reverse()(反转数组里的元素顺序,并返回数组本身)

1 var a = ['a', 'b', 'c'];
2 var b = a.reverse();        //a==>['c','b','a']    //b==>['c','b','a']

 

8、array.slice()(截取数组,左闭右开)

如果值为负数,则与array.length相加

1 var a = ['a', 'b', 'c'];
2 var b = a.slice(0,1);        //b==>['a']
3 var c = a.slice(1);          //c==>['a', 'b']
4 var d = a.slice(-2)          //d==>['a', 'b']
5 var e = a.slice(1,2);        //e==>['b', 'c']
6 var f = a.slice(-2,-1);      //f==>['b', 'c']

 

9、array.splice()(从数组中删除一个或多个元素,并用参数替换他们(有参数的话))

如果值为负数,则与array.length相加

1 var a = ['a', 'b' ,'c'];      //a==>['a','c']              删除
2 var r1 = a.splice(1,1);       //b==>['b']
3 
4 var b = ['a', 'b' ,'c'];      //b==>["a", "B", "b", "c"]   添加
5 var r2 = b.splice(1,0,'B');   //b==>[]
6 
7 var c = ['a', 'b' ,'c'];      //b==>["a", "B", "c"]        替换
8 var r3 = c.splice(1,1,'B');   //b==>['b']

 

10、array.sort()(对数组的内容进行排序)

1 var a = [4, 42, 15, 8, 16, 23];
2 a.sort();                     //a==>[15, 16, 23, 4, 42, 8]
3 a.sort(function(a, b){ //a==>[4, 8, 15, 16, 23, 42] 4 return a-b; 5 });

 

posted @ 2017-11-03 15:04  U炒饭  阅读(147)  评论(0编辑  收藏  举报