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