1. 数组的定义
Array() 是一个用来创建数组对象的构造器
var arr = new Array(1,2,3);
当然,我么也可以使用数组标识法
var arr = [1,2,3];
如果我们传递给 Array() 构造器的是一个数字,该数字就回被设为数组的长度,构造器会根据该长度创建数组,并将每个元素位置以 undefined 填充。
var arr = new Array(3);
a.length; //3
console.log(a); //[undefined, undefined, undefined]
2. Array 对象的成员属性和方法
length 返回数组中元素的个数
[1,2,3,4].length; //4
concat(i1, i2, i3, …) 合并数组
[1,2].concat([3,4],[5,6,7]); //[1, 2, 3, 4, 5, 6, 7]
join(separator) 将数组中的元素连成一个字符串,我们可通过参数来指定元素之间的分割字符串,默认值是逗号
[1,2,3].join(); //"1,2,3"
[1,2,3].join("|"); //"1|2|3"
[1,2,3].join(" is less than "); //"1 is less than 2 is less than 3"
pop() 移除数组中的最后一个元素,并将其返回,原数组改变
var a = ["one","two","three","four"];
var b = a.pop();
console.log(b); //four
console.log(a); //["one", "two", "three"]
push(i1, i2, i3, …) 将新元素添加到数组的末尾,并返回修改后数组的长度,原数组改变
var a = [];
var b = a.push("one", "two", "three");
console.log(b); //3
console.log(a); //["one", "two", "three"]
reverse() 反转数组中元素的顺序,并返回修改后的数组,原数组改变
var a = [1,2,3];
var b = a.reverse();
console.log(b); //[3,2,1]
console.log(a); //[3,2,1]
shift() 与pop()方法基本相同,移除的是首元素,并将其返回,原数组改变
var a = ["one","two","three","four"];
var b = a.shift();
console.log(b); //one
console.log(a); //["two", "three", "four"]
unshift(i1, i2, i3, …) 与push()方法类似,只不过元素将会被添加到数组的开始处,和push()方法一样,它也会在添加完元素后返回修改后的数组长度
var a = ["one","two","three","four"];
var b = a.unshift(1,2,3);
console.log(b); //7
console.log(a); //[1, 2, 3, "one", "two", "three", "four"]
slice(start_index, end_index) 截取数组的某一部分,截取时前包含后不包含”[ )”,原数组不变
var a = ["one","two","three","four"];
var b = a.slice(1,3);
console.log(b); //["two", "three"]
console.log(a);//["one", "two", "three", "four"]
sort(callback) 数组排序,它有一个可选参数,是一个回调函数,我们可以用它来自定义排序规则。callback函数以两个数组为参数,两个数组相等时返回0,第一个参数大时返回1,第二个参数大时返回-1,下面我们来演示一个按数字排序的自定义函数(默认是按照字符顺序排序的)
默认情况下是按照字符顺序排序的
var a = [101, 99, 1, 5];
a.sort();//[1, 101, 5, 99]
下面我们来自定义排序规则
function mySort(a, b) {
if(a > b) return 1;
if(a < b) return -1;
return 0;
}
var a = [101, 99, 1, 5];
a.sort(mySort); //[1, 5, 99, 101]
[33,22,11,13,1].sort(mySort); //[1, 11, 13, 22, 33]
splice(start, delete_count, i1, i2, i3, …) 该方法应该是数组函数中最强大的方法了,它可以在删除元素的同时添加新的元素。第一个参数是要删除元素的的开始位置,第二个参数是要删除的数组的个数,其余的参数则是一些将要插入在此处的新元素。该方法返回的是删除元素所组成的数组
var a = ["one","two","three","four"];
var b = a.splice(1, 2, "test1", "test2", "test3", 33);
console.log(b); //["two", "three"]
console.log(a); //["one", "test1", "test2", "test3", 33, "four"]