var arr1 = [1,2,3,4,5,6]; arr1[0]; arr1[1]; console.log("長度:"+arr1.length); 一、遍曆數組 / * i=下標*/ for(var i=0;i<arr1.length;i++){ console.log(arr1[i]); } ...
var arr1 = [1,2,3,4,5,6];
arr1[0];
arr1[1];
console.log("長度:"+arr1.length);
一、遍曆數組
/ * i=下標*/
for(var i=0;i<arr1.length;i++){
console.log(arr1[i]);
}
/*迴圈添加內容*/
var arr2 = new Array(6);
for(var i=0;i<arr2.length;i++){
arr2[i] = prompt("請輸入成績");
}
console.log(arr2);
/*添加數據的第二種辦法: push()*/
var arr3 = new Array(1,2,3);
arr3.push("a","b"); //預設添加至數組的最後
arr3.push("c");
console.log(arr3); //1,2,3,a,b,c
二、刪除數據
/*1. 刪除第一條數據: shift()*/
var arr4 = ["a","b","c","d","e","f"];
arr4.shift();
/*2.刪除最後一條數據: pop()*/
arr4.pop();
console.log(arr4.length);
console.log(arr4[4]);
/*3.刪除中間某一條數據: splice(起始下標,刪除多少項)*/
arr4.splice(2,1);
console.log(arr4);
console.log(arr4.length);//當發生刪除之後,數組長度會發生改變
console.log(arr4[4]);
三、替換數據
/*替換數據 : splice(起始下標,刪除多少項,替換的新數據)*/
var arr5 = ["a","b","c","d","e","f"];
arr5.splice(1,3,"bbbb");
console.log(arr5);
四、插入數據
/*插入數據: splice(起始下標,刪除多少項,替換的新數據)*/
arr5.splice(1,0,"bbbbbb");
console.log(arr5);//["a", "bbbbbb", "b", "c", "d", "e", "f"]
五、數組合併/*數組合併: concat()*/
var arr6 = [1,2,3];
var arr7 = [4,5,6];
var newarr = arr6.concat(arr7); //返回一個合併了的新數組
var newarr = arr6.concat("a","b"); //返回一個合併了的新數組
console.log(arr6);
console.log(arr7);
console.log(newarr);
六、數組抽取
/*數組抽取: slice(起始下標,結束下標不包含自己)*/
var arr8 = [1,2,3,4,5,6];
var newarr2 = arr8.slice(2,-1);
/*通過返回一個slice後的新數組 負數代表從最後開始倒數*/
console.log(arr8);
console.log(newarr2);
七、數組排序
/*數組排序*/
var arr9 = [3,2,1,6,4,7,5];
var arr10 = arr9;
var arr10 = [];
/*Array複製的方法*/
for(var i=0;
i<arr9.length;i++){
arr10[i]=arr9[i];
}
arr9.sort(); //從小到大進行排序
console.log(arr9);
console.log(arr10);
/*數組串聯: join("串起來的符號")*/
var arr11 = [1,2,3,4,5,6];
var newarr3 = arr11.join("+");
console.log(arr11);
console.log(newarr3); //把所有數組內的數據通過制定符號串聯起來