何時該用陣列(Array)
當你需要儲存多筆同類型、有順序的資料,並且之後要對這群資料做有條理的批次處理(如查詢、新增、刪除、計算、轉換)
基本觀念
1.陣列的寫法
let colors = ['blue','red','black'];
2.陣列能放數字
let books = [5 ,30 ,400 ,100];
console.log(books); //輸出[5 ,30 ,400 ,100]
3.陣列放混合資料
let ary = ['blue',5,false];
console.log(ary); // 輸出['blue', 5, false]
讀取陣列資料
let colors = ['blue','red','black'];
console.log(colors[0]); //讀取第一筆資料 ,blue
console.log(colors[1]); //讀取第二筆資料 ,red
讀取陣列資料 ,並賦予新變數
let colors = ['blue','red','black'];
let a = colors[2];
console.log(a); //輸出black
length讀取陣列長度
let colors = ['blue','red','black'];
let a = colors.length; //呼叫a ,顯示4的結果
console.log(colors.length); //輸出 4
寫入、新增、刪除資料
let colors = []; // 設一陣列為空值
colors[0] = "blue"; //第一筆寫入
colors[1] = "red"; //第二筆寫入
colors[2] = "yewllo"; //第三筆寫入
colors[3] = "pink"; //第四筆寫入
console.log(colors); //輸出 ['blue', 'red', 'yewllo', 'pink']
console.log(colors.length);//輸出 4
colors.push('blue'); // 尾端新增
console.log(colors); //輸出 ['blue', 'red', 'yewllo', 'pink', 'blue']
colors.unshift('green'); // 開頭新增
console.log(colors);//輸出 ['green', 'blue', 'red', 'yewllo', 'pink', 'blue']
colors.pop(); // 刪除最後一筆
console.log(colors);//輸出 ['green', 'blue', 'red', 'yewllo', 'pink']
colors.shift(); // 刪除第一筆
console.log(colors);//輸出 ['blue', 'red', 'yewllo', 'pink']
splice是用來刪除指定資料
shift 和 splice 都是用來修改陣列內容的方法,但用途不同
let colors = ['blue','red','black'];
colors.splice (1,1); //第一個數字是起始位置,第二個數字是往後刪除幾筆資料
console.log(colors); //輸出 ['blue', 'black']