1 /*Array对象构造函数*/
2
3 /*组合记忆 shift unshift pop push
4 添加和删除
5 shift unshift 从数组开头开始添加或者删除
6 pop push 从数组末尾添加或者删除
7 */
8
9 //shift:删除原数组第一项,并返回删除元素的值;如果数组为空则返回undefined
10 var arr1 = [1,2,3,4,5];
11 var arr2 = [1,2,3,4,5];
12 var result = arr1.shift();
13 console.log(result);//a:[2,3,4,5] b:1
14
15 //unshift:将参数添加到原数组开头,并返回数组的长度
16 arr1 = [1,2,3,4,5];
17 result = arr1.unshift(-2,-1);
18 console.log(result);//a:[-2,-1,1,2,3,4,5] b:7
19 //注:在IE6.0下测试返回值总为undefined,
20 //FF2.0下测试返回值为7,所以这个方法的返回值不可靠,需要用返回值时可用splice代替本方法来使用。
21
22
23 //pop:删除原数组最后一项,并返回删除元素的值;如果数组为空则返回undefined
24 arr1= [1,2,3,4,5];
25 result = arr1.pop();
26 console.log(result);//a:[1,2,3,4] b:5
27
28 //push:将参数添加到原数组末尾,并返回数组的长度
29 arr1 = [1,2,3,4,5];
30 result = arr1.push(6,7);
31 console.log(result);//a:[1,2,3,4,5,6,7] b:7
1 /*数组合并concat*/
2
3 //concat:返回一个新数组,是将参数添加到原数组中构成的
4 arr1 = [1,2,3,4,5];
5 result = arr1.concat(6,7);
6 console.log(result);//a:[1,2,3,4,5] b:[1,2,3,4,5,6,7]
1 /*排序 sort 从小到大 reverse 从大到小*/
2 // sort(orderfunction):按指定的参数对数组进行排序
3 arr1 = [1,2,3,4,5];
4 result = arr1.sort();
5 console.log(result);//[1,2,3,4,5]
6
7 // reverse:将数组反序
8 arr1 = [1,2,3,4,5,8,34];
9 result = arr1.reverse();
10 console.log(result);//[34,8,5,4,3,2,1]
1 // slice(start,end):返回从原数组中指定开始下标到结束下标之间的项组成的新数组,但不包括结束位置的项
2 arr1 = [1,2,3,4,5];
3 result = arr1.slice(2,5); //[3,4,5]
4 result = arr1.slice(2); //[3,4,5] 在只有一个参数的情况下,slice()方法返回从该参数指定位置开始到当前数组末尾的所有项;
5
6 //返回自身
7 result = arr1.slice(0); //返回自身
1 /*join(separator) 数组拼接成字符串*/
2 //将数组的元素组起一个字符串,以separator为分隔符,省略的话则用默认用逗号为分隔符
3 arr1 = [1,2,3,4,5];
4 result = arr1.join("|"); //a:[1,2,3,4,5] b:"1|2|3|4|5"
1 /*splice*/
2 //splice(start,deleteCount,val1,val2,...):
3 // 从start位置开始删除deleteCount项,并从该位置起插入val1,val2,...
4 arr1 = [1,2,3,4,5];
5 result = arr1.splice(2,2,7,8,9); //a:[1,2,7,8,9,5] b:[3,4]
6 result = arr1.splice(0,1); //同shift
7
8 arr1.splice(0,0,-2,-1);
9 result = arr1.length; //同unshift
10
11 result = arr1.splice(arr1.length-1,1); //同pop
12 arr1.splice(arr1.length,0,6,7);
13 result = arr1.length; //同push
1 <script>
2 /*--数组扩展方法--*/
3 /*
4 *去除数组中的重复项
5 */
6 Array.prototype.unique = function() {
7 var a = []; var l = this.length;
8 for (var i = 0; i < l; i++)
9 {
10 for (var j = i + 1; j < l; j++)
11 {
12 if (this[i] === this[j]) j = ++i;
13 }
14 a.push(this[i]);
15 }
16 return a;
17 };
18
19 var arr = [1,2,3,4,5,6,6,7,7,77,7,]
20 console.log(arr.unique());//Array(8)
21
22 </script>