定义
定义空数组
var arr = new Array();
var arr = [];
定义一个包含1,2,3的数组
var arr = [1,2,3];
var arr = new Array(1,2,3);
插入
push():数组的末尾加入值
1
2
3
4
5
6
|
var arr = new Array();
for ( var i = 1;i<7;i++){
arr.push(i);
}
console.log(arr);
|
unshift(elem1,elem2,elem3):数组的开头添加数据
1
2
3
4
|
var arr = [1,2,3];
arr.unshift(4,5);
console.log(arr);
|
splice(index,num,elem1,elem2,elem3….):当num为0的时候splice表示在index的位置插入elem1,elem2,elem3….,index下标和数组下标一样,表示在某个数的后面插入。
1
2
3
4
|
var arr = [7,8,9];
arr.splice(2,0,4,5,6);
console.log(arr);
|
删除
splice(index,num):从下标index开始删除num个
1
2
3
4
|
var arr = new Array(1,2,3,4,5,6);
arr.splice(1,3);
console.log(arr);
|
pop():删除数组的最后一个值并返回
1
2
3
4
5
|
var arr = new Array(1,2,3,4,5,6);
var tmp = arr.pop();
console.log(arr);
console.log(tmp);
|
shift():删除第一个值并返回
1
2
3
4
5
|
var arr = new Array(1,2,3,4,5,6);
var tmp = arr.shift();
console.log(arr);
console.log(tmp);
|
截取
slice(start,[end]):选取[start,end)区间内的数组值,注意end是取不到的,若不写end则默认数组长度
1
2
3
4
5
|
var arr = new Array(1,2,3,4,5,6);
var new_arr = arr.slice(2,4);
console.log(arr.slice(2,4));
console.log(new_arr);
|
合并
arr1.concat(arr2,arr3….):将数组arr1和arr2,arr3…进行合并
1
2
3
4
5
6
|
var arr1 = new Array(1,2,3);
var arr2 = [4,5,6];
var arr3 = [7];
var new_arr = arr1.concat(arr2,arr3);
console.log(new_arr);
|
数组转化字符串
join(separator):返回由separator分隔的字符攒
1
2
3
4
|
var arr = [1,2,3,4,5,6];
var str = arr.join( '-' );
console.log(str);
|
排序
sort(func):默认按照字典序从小到大排序,若希望数值/从大到小排序需要些func函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
var arr1 = [45,123,67,89,90];
console.log(arr1.sort());
var arr2 = [45,123,67,89,90];
function sort_num1(a,b){
return a-b;
}
console.log(arr2.sort(sort_num1));
var arr3 = [45,123,67,89,90];
function sort_num2(a,b){
return b-a;
}
console.log(arr3.sort(sort_num2));
var arr4 = [45,123,67,89,90];
function sort_num3(a,b){
return String(a)<String(b);
}
console.log(arr4.sort(sort_num3));
|
分类: Javascript