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