--- title: 陣列 tags: 陣列, array, push, unshift, pop, shift description: --- 陣列 Array === ### 什麼是陣列? - 陣列可看做**資料的集合**。 顏色 ```let colors = ['red', 'blue', 'yellow']``` 人名 ```let names = ['john', 'wayne', 'peter']``` - 陣列內除了放```string```,也能放```number```、```boolean```、```undefined```、```null```。 ```javascript= let data = ['john', '20', false, undefined, null] ``` - 陣列裡面也能放物件```Object```。 ```javascript= let person = [ { name: 'John', age: 21, bloodType: 'b', }, { name: 'wayne', age: 25, bloodType: 'o', }, ]; ``` ### 如何讀取陣列的資料、資料長度 ```javascript= let array = ['red', 'blue', 'yellow']; console.log(array[2]); // yellow console.log(array.length); // 3 ``` - **取得陣列的資料** 陣列內資料筆數的順序,稱為索引值```index```。索引值==從0==開始計算(**0就是陣列的第一筆資料**),依序到最後一筆資料。 要取得某陣列的**第n筆**資料,index值就是```n - 1``` 例:陣列array的==第三筆資料==的值,可寫成```array[2]```。 - **取得陣列的資料長度** 在陣列變數名稱加上```.length```,便會回傳陣列資料的長度。 例:```array.length``` - **由資料長度得知==索引值最大值==** 陣列資料**長度**的計算,是**從1**開始計算。 陣列資料**索引值**的計算,是**從0**開始計算。 因此將陣列資料長度==減去1==,就能得知**索引值最大值**。 例:```array.length - 1``` <br> ### 陣列如何寫入資料 - **指定index值寫入陣列** 1. 先建立變數color,賦予空陣列。 ```let colors = [];``` 2. 再針對陣列colors第二筆資料賦予字串 ```colors[1] = 'red';``` 3. 查看陣列colors得知==資料長度為2== ![](https://i.imgur.com/klJARRu.png) :::success 因為是對第二筆資料賦予字串,跳過了第一筆資料。 實際上**陣列colors保留了第一筆資料的位置**,所以資料長度為2 ::: 所以陣列顯示時,在陣列資料==第一筆==的位置顯示```empty```空的 ,用```console.log(colors[0])```會印出```undefined```。 - **push寫入資料```.push()```** 被push進去的資料,會被放入陣列裡==最後一個==```index```的位置。 ```javascript= let data = []; data.push(1); data.push('a'); data.push('b'); console.log(data); // [1, 'a', 'b'] ``` <br> - **unshift寫入資料```.unshift()```** 被unshift進去的資料,會被放入陣列裡==第一個==```index```的位置。 :::success 有時要把**最新**的資料放在最物件前面,這時就能用```.ushift```,把資料加入放在物件的最前面。 ::: ```javascript= let data = []; data.unshift(1); data.unshift('a'); data.unshift('b'); console.unshift(data); // ['b', 'a', 1] ``` ### 陣列如何刪除資料 - **pop刪除資料** 被pop的陣列資料,會把陣列裡==最後一筆==資料刪除。 ```javascript= let data = ['a', 'b', 'c']; data.pop(); data.pop(); console.log(data); // ['a'] ``` - **shift刪除資料** 被shift的陣列資料,會把陣列裡==第一筆==資料刪除。 ```javascript= let data = ['a', 'b', 'c']; data.shift(); data.shift(); console.log(data); // ['c'] ``` ### 陣列如何指定刪除資料 - **splice刪除指定資料```.splice()```** - index:刪除陣列的起始位置,也就是陣列的```index```。 - n:要**往後**連續刪除n筆資料。 ```javascript= colors.splice(index, n); ``` - 範例 ```javascript= let colors = ['red', 'blue', 'yellow']; colors.splice(0, 2); console.log(colors); // ['yellow'] ``` - **delete清除指定資料```delete```** - 把陣列**指定的`index`位置的值清除**,`index`位置仍保留著,為`empty`。`console.log`印出為`undefined`。 ```javascript= delete array[index]; ``` - 範例 ```javascript= let colors = ['red', 'blue', 'yellow']; console.log(colors); // ["red", "blue", empty] console.log(colors[2]); // undefined ```