前端寶庫

前端技術分享平台

0%

[速查表]_Array

各種常用 Array語法 速查表

  • 操作方法分類

    分類 方法
    會改變原始陣列 push()pop()shift()unshift()reverse()splice()sort()copyWithin()fill()
    回傳陣列元素資訊或索引值 lengthat()indexOf()lastIndexOf()find()findIndex()filter()
    針對每個元素處理 forEach()
    產生新的陣列或新的值 concat()slice()map()reduce()reduceRight()flat()flatMap()
    Array.from()Array.of()
    回傳迭代器(Iteration) entries()keys()values()
    回傳字串 join()toString()
    判斷並回傳布林值 every()some()includes()Array.isArray()
  • 會改變原始陣列

    • push()

      push() 可以將一個或多個元素,加入陣列後方,並回傳修改後的陣列。

      let a = [1, 2, 3, 4];
      a.push(5, 6);
      console.log(a); // [1, 2, 3, 4, 5, 6]
    • pop()

      pop() 從陣列移除(取出)最後一個元素。

      let a = [1, 2, 3, 4];
      let b = a.pop();
      console.log(a); // [1, 2, 3]
      console.log(b); // [4]
    • shift()

      shift() 從陣列移除(取出)第一個元素。

      let a = [1, 2, 3, 4];
      let b = a.shift();
      console.log(a); // [2, 3, 4]
      console.log(b); // [1]
    • unshift()

      shift() 可以將一個或多個元素,加入陣列前方,並回傳修改後的陣列。

      let a = [1, 2, 3, 4];
      a.unshift(5, 6);
      console.log(a); // [5, 6, 1, 2, 3, 4]
    • reverse()

      reverse() 將陣列作反向排序。

      let a = [1, 2, 3, 4];
      a.reverse();
      console.log(a); // [4, 3, 2, 1]
    • splice()

      splice() 可以移除或新增陣列的元素。
      包含三個以上參數:

      • 第一個:要從哪個元素索引值開始,索引從0開始。
      • 第二個:要移除的總筆數,若省略,則從刪除起點開始的所有元素都會被刪除;若設為0或負數,則不移除元素。
      • 第三個以上:要添加的元素,若省略,則原陣列資料不會添加新資料,表示不增加只刪除。
      let a = [1, 2, 3, 4, 5];

      // 刪除一筆資料
      a.splice(2, 1);
      console.log(a); // [1, 2, 4, 5] 3被移除

      // 刪除索引之後的所有元素
      a.splice(1);
      console.log(a); // [1] 2以後的所有元素被移除

      // 取代
      a.splice(2, 3, 100, 200, 300);
      console.log(a); // [1, 2, 100, 200, 300] 3,4,5被移除,並添加100,200,300

      // 不刪除,僅添加
      a.splice(2, 0, 100);
      console.log(a); // [1, 2, 100, 3, 4, 5] 在索引2的地方添加100
    • sort()

      sort() 可以針對陣列的元素進行排序,裡頭包含了一個排序用的判斷函式,
      函式內必須包含兩個參數,這兩個參數分別代表陣列裡第 n 個和第 n+1 個元素,
      透過比較第 n 和第 n+1 個元素的大小來進行排序。
      會改變原本的陣列內容。

      let nums = [99, 999, 88, 888, 666];

      // 由小到大排列
      nums.sort((a,b) => a - b);
      console.log(nums); // [88, 99, 666, 888, 999]

      // 由大到小排列
      nums.sort((a,b) => b - a);
      console.log(nums); // [999, 888, 666, 99, 88]

      如果不使用判斷函式,預設會將元素轉換成字串,並採用 unicode 來判斷。

      let nums = [99, 999, 88, 888, 666];

      nums.sort();
      console.log(nums); // [666, 88, 888, 99, 999]
    • copyWithin()

      copyWithin() 複製陣列中的元素,並置換原始陣列中的元素。
      包含三個參數:

      • 第一個是要置換的位置 (必填)。
      • 第二個是複製起點的索引值 (選填,預設0)。
      • 第三個是複製終點的索引值+1 (選填,預設等於陣列長度)。

      處理後的陣列長度必須等於原本的長度,超過的部分會被移除。

      let nums = [1,2,3,4,5,6];

      nums.copyWithin(2);
      console.log(nums); // [1,2,1,2,3,4] (5,6被移除)

      nums.copyWithin(3, 1, 3);
      console.log(nums); // [1,2,3,2,3,6]
    • fill()

      fill() 用一個指定的值置換陣列中所有元素。
      包含三個參數:

      • 第一個是指定要置換的值 (必填)。
      • 第二個是置換起點的索引值 (選填,預設0)。
      • 第三個是置換終點的索引值+1 (選填,預設等於陣列長度)。
      let nums = [1,2,3,4,5,6];

      nums.fill('a');
      console.log(nums); // ['a','a','a','a','a','a']

      nums.fill('b', 2, 5);
      console.log(nums); // [1,2,3,'b','b',6]
  • 回傳陣列元素資訊或索引值

    • length

      length 可以取得陣列的長度(所有元素的數量)。

      let a = [1, 2, 3, 4];
      console.log(a.length); // 4
    • at()

      at 接收一個索引值,並返回該元素。
      類似 array[index]。
      參數:

      • index 要返回的陣列元素的索引位置,若為負數,則從陣列的尾端開始尋找 (必填)。
      const cart = ['apple', 'banana', 'pear'];

      console.log(arr.at(-1)); // 'pear'

      cart.push('orange');
      console.log(arr.at(-1)); // 'orange'
    • indexOf()

      indexOf 在陣列中搜尋指定元素,回傳第一個符合條件的元素的索引值;若沒找到,則回傳 -1。
      參數:

      • 第一個參數為 要查找的值 (必填)。
      • 第二個參數為 搜尋起點的索引值 (選填,預設為0)。
      let fruits = ['蘋果', '香蕉', '芭樂', '芭樂', '番茄'];

      console.log(fruits.indexOf('香蕉')); // 1,代表元素在索引值 1

      console.log(fruits.indexOf('芭樂')); // 2,只會回傳第一個符合的元素索引值

      console.log(fruits.indexOf('榴槤')); // -1,表示陣列中無此資料

      console.log(fruits.indexOf('香蕉', 3)); // -1,從索引值 3 開始尋找,沒找到
    • lastIndexOf()

      lastIndexOf 在陣列中搜尋指定元素,將會回傳最後一個符合條件的元素的索引值,若在陣列中沒找到則回傳 -1。
      參數:

      • 第一個參數為 要查找的值 (必填)。
      • 第二個參數為 由後向前搜尋的起點索引值 (選填,預設為整個陣列長度-1)。
      let fruits = ['蘋果', '香蕉', '芭樂', '芭樂', '番茄'];

      console.log(fruits.lastIndexOf('芭樂')); // 3,只會回傳最後一個符合的元素索引值

      console.log(fruits.lastIndexOf('香蕉', 3)); // 1,從索引值3往回找。
    • find()

      find 回傳第一個滿足條件的值,如果找不到則回傳 undefined。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      let array = [5, 12, 8, 130, 44];

      console.log(array.find(ele => ele > 10)); // 12 (回傳第一個滿足條件的值)
      console.log(array.find(ele => ele < 0)); // undefined
    • findIndex()

      findIndex 回傳第一個滿足條件的索引值,如果找不到則回傳 -1。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      let array = [5, 12, 8, 130, 44];

      console.log(array.findIndex(ele => ele > 13)); // 3 (回傳第一個滿足條件的索引值)
      console.log(array.findIndex(ele => ele < 0)); // -1
    • filter()

      filter 回傳所有符合條件的值,組成新陣列。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      let words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

      console.log(words.filter(w => w.length > 6));
      // ["exuberant", "destruction", "present"]
  • 針對每個元素處理

    • forEach()

      forEach 會將陣列中的每個元素,皆傳入函式中執行。
      無法使用 break 中斷,若需中斷執行,請改用傳統的 for 迴圈。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      let nums = [1, 2, 3, 4, 5];

      nums.forEach(n => console.log(n));
      /*
      1
      2
      3
      4
      5
      */

      若想改變原始陣列,可善用索引值

      let nums = [1, 2, 3, 4, 5];

      nums.forEach((item, index, arr) => {
      arr[index] = item * 10;
      })
      consolse.log(nums); // [10, 20, 30, 40, 50]
  • 產生新的陣列或新的值

    • concat()

      concat 可以將多個陣列合併在一起,也可使用擴展運算符 ... 來代替。

      let num1 = [1, 2, 3];
      let num2 = [4, 5, 6];
      let num3 = [7, 8, 9];

      let nums = num1.concat(num2, num3);
      let spread = [...num1, ...num2, ...num3];
      console.log(nums); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
      console.log(spread); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

      注意:合併巢狀陣列 (concat 只有淺拷貝)

      let num1 = [[1]];
      let num2 = [2, [3]];

      var nums = num1.concat(num2);
      console.log(nums); // [[1], 2, [3]]

      num1[0].push(4);
      console.log(nums); // [[1, 4], 2, [3]]
    • slice()

      slice 擷取原始陣列之 beginend (不含end) 部分的淺拷貝,回傳一個新陣列物件。
      包含兩個參數:

      • begin (選填,預設為0),
        從哪一個索引值開始提取拷貝 (起始為0),
        可使用負數,表示由陣列末端索引開始提取。
      • end (選填,預設為陣列長度),
        至哪一個索引值之前停止提取,不含end (起始為0),
        可使用負數,表示到陣列末端索引結束提取,
        若大於陣列長度,會提取至陣列最後一個元素。
      const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

      console.log(animals.slice()); // ['ant', 'bison', 'camel', 'duck', 'elephant']
      console.log(animals.slice(2)); // ['camel', 'duck', 'elephant']
      console.log(animals.slice(2, 4)); // ['camel', 'duck']
      console.log(animals.slice(-2)); // ['duck', 'elephant']
      console.log(animals.slice(2, -1)); // ['camel', 'duck']
    • map()

      map 將原陣列的每一個元素經由回呼函式運算後,回傳一個新陣列物件。
      map 會處理每一個元素,就算不 return,也會出現 undefined,此時可先透過 filter 篩選過後,再使用 map
      若不需要回傳新陣列,可改用 forEach
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      const nums = [1, 2, 3, 4];
      const maps = nums.map(x => x + 10);

      console.log(maps); // [11, 12, 13, 14]
    • reduce()

      reduce 將陣列中每個元素進行運算,每次函式的回傳值會當作下一次函式的傳入值,最後回傳最終結果。
      空值會略過。
      若初始計算的數值未提供,會跳過第一個陣列索引,從索引1開始執行回呼函式。
      若有提供初始計算的數值,則會由陣列索引0開始執行。
      不只可加總數字,也可做字串串接。
      參數:

      • 含有一個 callback 函式參數 (必填) 和初始計算的數值 (選填,預設為陣列的第一個值)。
      • 函式中有兩個必填參數及兩個選填參數:
        • 累加器,用來累積函式每一次執行的回傳值 (必填)
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
      const nums = [1, 2, 3, 4];
      const reducer = (previousVal, current) => previousVal + current;

      console.log(nums.reduce(reducer)); // 10
      console.log(nums.reduce(reducer, 5)); // 15,初始計算值:5

      HTML字串加總範例

      const lists = ['第一項', '第二項', '第三項'];
      const reducer = (previousVal, current) => `${previousVal}<li>${current}</li>`;

      const ulTag = document.createElement('ul');
      ulTag.append(lists.reduce(reducer, ''));

      console.log(ulTag);
      // <ul><li>第一項</li><li>第二項</li><li>第三項</li></ul>
    • reduceRight()

      reduceRightreduce 大同小異,只是其計算方式是由右到左,
      對於加法來說沒什麼影響,旦對於減法而言就有差異。

      const nums = [1, 2, 3, 4];
      const reducer = (accumulator, current) => accumulator - current;

      console.log(nums.reduce(reducer)); // -2
    • flat()

      flat 可以將一個多維陣列的深度轉成一維 (扁平化),
      如果深度有很多層,可使用 Infinity 來全部展開成一維陣列。
      參數:

      • depth,指定要轉換的結構深度 (選填,預設為1)。
      const arr1 = [0, 1, 2, [3, 4]];
      console.log(arr1.flat()); // [0, 1, 2, 3, 4]

      const arr2 = [0, 1, 2, [[[3, 4]]]];
      console.log(arr2.flat(2)); // [0, 1, 2, [3, 4]]

      // 使用 Infinity,可展開任意深度的陣列
      var arr3 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
      arr3.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      // flat() 會移除陣列中的空值
      var arr4 = [1, 2, , 4, 5];
      arr4.flat(); // [1, 2, 4, 5]
    • flatMap()

      flatMap 等於 map()flat() 的組合,在運算後直接將陣列扁平化處理。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      const arr1 = [0, 1, 2, 4];

      arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8]

      arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]
    • Array.from()

      Array.from() 會將 『類陣列物件』、『可迭代的物件』轉換成陣列。
      類陣列物件:擁有一個length屬性和若干索引屬性的任務對象。
      可迭代物件:可以獲取對象中的元素,如 MapSet 等。
      參數:

      • arrayLike 想要轉換成數組的類陣列或可迭代對象 (必填)。
      • mapFn 新陣列中的每個元素會執行該回呼函式 (選填)。
      • this 執行回呼函式mapFn時 this 對象 (選填)。
      console.log(Array.from('foo'));                     // ['f', 'o', 'o']
      console.log(Array.from([1, 2, 3], x => x + x)); // [2, 4, 6]
    • Array.of()

      Array.of() 可以快速將數字、字串等內容,轉換成陣列。
      Array.of() 與 Array 建構式之間的不同在於如何處理整數引數:
      Array.of(7) 會建立一個擁有單個元素—7—的陣列,
      而 Array(7) 會建立一個 length 屬性值為 7 的空陣列(註:這意味著這個陣列有 7 個空缺欄位(empty slots),而非 7 個值為 undefined 的欄位)。
      參數:

      • elementN 要用來成為新建立之陣列的元素。
      Array.of(7);          // [7]
      Array.of(1, 2, 3); // [1, 2, 3]

      Array(7); // [ , , , , , , ]
      Array(1, 2, 3); // [1, 2, 3]
  • 回傳迭代器 (Iteration)

    • 什麼是迭代?

      迭代指的是對物件重複同樣的處理方式,每重複一次就稱為一次迭代。
      JavaScript 中迭代大部分指的是迴圈,但陣列中也有類似迴圈功能的方法,
      這些方法會產生「迭代器」來達成類似迴圈的效果。
      #產生器物件(Generator object)
      #委派(yield *)
      #建立產生器(function *)

      Summer。桑莫。夏天 - 產生器(Generator)

    • 回傳迭代器物件的陣列方法

      有些方法回傳的不是新陣列或是特定的值,而是一個陣列迭代器物件,
      要操作或是讀取該物件的值就需要使用 for...of 語法。
      for...of 除了用在陣列以外,也可用在 字串mapset 等等…

      for( let 元素 of 迭代器){
      執行動作...
      }

      迭代器用法

      let a = ['w', 'y', 'k', 'o', 'p'];
      let iterator = a.values();

      console.log(iterator.next().value); // w
      console.log(iterator.next().value); // y
      console.log(iterator.next().value); // k
      console.log(iterator.next().value); // o
      console.log(iterator.next().value); // p
    • entries()

      entries 會回傳一個新陣列迭代器物件,包含陣列中每一索引值與元素的配對。

      let fruits = ['蘋果', '香蕉', '芭樂', '木瓜', '番茄'];
      let iterator = fruits.entries();

      for(let value of iterator){
      console.log(value);
      }
      /*
      [0, "蘋果"]
      [1, "香蕉"]
      [2, "芭樂"]
      [3, "木瓜"]
      [4, "番茄"]
      */
    • keys()

      keys 回傳陣列中的每一個索引值(key)成為新的 Array Iterator 物件 (迭代器物件)。
      需要使用 for...of 來讀取迭代器的值。
      或使用 Array.from()解構賦值(展開) 轉換成陣列。

      let arr = ['a', 'b', 'c', 'd'];
      let getKeys = arr.keys();

      for(let key of getKeys) {
      console.log(key);
      /*
      0
      1
      2
      3
      */
      };

      let fromKeys = Array.from(getKeys);
      let denseKeys = [...getKeys];
      console.log(fromKeys); // [0, 1, 2, 3]
      console.log(denseKeys); // [0, 1, 2, 3]
    • values()

      values 回傳陣列中的每一個元素的值成為新的 Array Iterator 物件 (迭代器物件)。
      需要使用 for...of 來讀取迭代器的值。

      let arr = ['a', 'b', 'c', 'd'];
      let getVals = arr.values();

      for(let value of getVals) {
      console.log(value);
      };
      /*
      a
      b
      c
      d
      */
  • 回傳字串

    • join()

      join 可以將陣列中所有元素,藉由指定的字符合併在一起變成字串呈現,若沒有指定字符預設會用「逗號」合併。
      任何 undefined 或 null 的元素都會被視為空字串處理。
      參數:

      • 含有一個串接符號參數 (選填,預設 ,)
      const elements = ['Fire', 'Air', 'Water'];

      console.log(elements.join()); // Fire,Air,Water
      console.log(elements.join('')); // FireAirWater
      console.log(elements.join('--')); // Fire--Air--Water
    • toString()

      toString() 將陣列以字串方式回傳。
      Array 覆寫了 Object 中的 toString 方法。
      陣列的 toString 方法會將陣列中的每個元素用逗號串接起來成為一個字串,並回傳該字串。
      在會以文字型態表示的地方使用了陣列,或是在字串的串接中使用到了陣列,JavaScript 會自動為該陣列使用toString 方法。

      const array1 = [1, 2, 'a', '1a'];
      console.log(array1.toString()); // '1,2,a,1a'
  • 判斷並回傳布林值

    • every()

      every 會測試陣列中的所有元素,是否都通過了由給定之函式所實作的測試,並回傳布林值。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      const array1 = [1, 30, 39, 29, 10, 13];

      console.log(array1.every(e => e < 40)); // true
      console.log(array1.every(e => e > 30)); // false
    • some()

      some 會測試陣列中的至少有一個元素,通過由給定之函式所實作的測試,並回傳布林值。
      參數:

      • 含有一個 callback 函式參數。
      • 函式中有一個必填參數及三個選填參數:
        • 每個被迭代的元素 (必填)
        • 目前處理的元素索引值 (選填)
        • 使用該方法的陣列 (選填)
        • 執行此函式的 this 值 (選填)
      const array1 = [1, 2, 3, 4, 5];

      console.log(array1.some(e => e % 2 === 0)); // true (至少有一個元素是偶數)
    • includes()

      includes 會判斷陣列中是否包含某個元素,並以此回傳 true 或 false。
      參數:

      • searchElement 要搜索的元素 (必填)。
      • fromIndex 搜尋起點的索引值,
        若為負數值,則搜尋起點將會是陣列長度 + 此參數的值。
        若fromIndex大於或等於陣列長度,會回傳 false (選填,預設0)。
      [1, 2, 3].includes(2);      // true
      [1, 2, 3].includes(4); // false
      [1, 2, 3].includes(3, 3); // false
      [1, 2, 3].includes(3, -1); // true
      [1, 2, NaN].includes(NaN); // true
    • Array.isArray()

      Array.isArray() 能判斷一個物件是否為陣列,並回傳 true 或 false。
      參數:

      • obj 要檢查的物件 (必填)。
      // 下方都回傳 true
      Array.isArray([]);
      Array.isArray([1]);
      Array.isArray(new Array());
      Array.isArray(new Array('a', 'b', 'c', 'd'));
      Array.isArray(new Array(3));
      // 小細節:Array.prototype 本身是陣列:
      Array.isArray(Array.prototype);

      // 下方都回傳 false
      Array.isArray();
      Array.isArray({});
      Array.isArray(null);
      Array.isArray(undefined);
      Array.isArray(17);
      Array.isArray('Array');
      Array.isArray(true);
      Array.isArray(false);
      Array.isArray({ __proto__: Array.prototype });

      instanceof vs isArray
      當檢查Array實例時,Array.isArray 相較於 instanceof 更加推薦,因為它可以穿透 iframes

      var iframe = document.createElement('iframe');
      document.body.appendChild(iframe);
      xArray = window.frames[window.frames.length-1].Array;
      var arr = new xArray(1,2,3); // [1,2,3]

      // 正確地檢查陣列型態
      Array.isArray(arr); // true
      // 它不能在 iframes 之間正常運作
      arr instanceof Array; // false