JavaScript內建物件之Array
阿新 • • 發佈:2018-11-19
Array物件為JavaScript內建的陣列物件
一、Array物件的建立
1. 建立陣列物件
var week = new Array(7);
var books = new Array();//可以不指定陣列的長度
2. 初始化陣列物件
var week = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var test1 = [100,200,300];
var test2 = [100,"abcd",200];
3. 獲取陣列元素的個數:length 屬性
4. 建立二維陣列
var week = new Array(7);
for(var i = 0 ; i < 7 ;i ++){
week[i] = new Array(2);
}
week[0][0] = "星期日";
week[0][1] = "Sunday";
week[1][0] = "星期一";
week[1][1] = "Monday";
...
week[6][0] = "星期六";
week[6][1] = "Saturday";
二、Array物件的常用方法
1. 陣列轉換為字串
- x.join([str]) :str作為連線陣列中元素的字串,可省
- x.toString() :用“,”逗號連線陣列成為字串
var arr = [1,2,3,4];
alert(arr.join("<"));//1<2<3<4
alert(arr.toString());//1,2,3,4
2. 連線陣列
- x.concat(value,....) :value 作為陣列元素連線到陣列的末尾
var a = [1,2,3];
var b = a.concat(4,5,6,7);
alert(a.toString());//1,2,3
alert(b.toString());//1,2,3,4,5,6,7
3. 獲取子陣列
- x.slice(start,[end]) :start位置開始索引;end為結束位置加1,省略則從start位置擷取以後陣列的所有元素。
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1.slice(2,5);
alert(arr2.toString());//c,d,e
var arr3 = arr1.slice(2);
alert(arr3.toString());//c,d,e,f
4.陣列反向與排序
- x.reverse() :反向陣列,改變陣列中數值的順序
var arr1 = [12,23,34,45,56];
alert(arr1.reverse().toString());//56,45,34,23,12
- x.sort([sortFunction]) :陣列排序,sortFunction :可選項,用來確定元素順序的函式的名稱
var arr = [12,2,4536,23];
alert(arr.sort().toString());//12,2,4536,23
alert(arr.sort(sortFunction).toString());//2,12,23,4536
function sortFunction(a,b){
return a-b;
}