1. 程式人生 > 實用技巧 >JS30 - 04 Array Cardio Day 1

JS30 - 04 Array Cardio Day 1

效果展示

相關知識

  1. Array.prototype.filter()

    • 篩選出執行結果為 true 的元素,組成一個新陣列返回

    • 例:選出 length > 6 的 word

    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
        
    const result = words.filter(word => word.length > 6);
        
    console.log(result);
    // expected output: Array ["exuberant", "destruction", "present"]
    
  2. Array.prototype.map()

    • 把陣列中的每個元素進行處理後,返回一個新的陣列

    • 例:將一陣列的各元素都乘以 2,返回一個新陣列

    const array1 = [1, 4, 9, 16];
        
    // pass a function to map
    const map1 = array1.map(x => x * 2);
        
    console.log(map1);
    // expected output: Array [2, 8, 18, 32]
    
  3. Array.prototype.sort()

    • 對陣列的元素進行排序,詳見 MDN: Array.prototype.sort()

    • 語法:arr.sort([compareFunction])

    • 比較函式(compareFunction)格式

    function compare(a, b) {
      if (a < b ) {           // 按某種排序標準進行比較, a 小於 b
        return -1;            // a 被排列到 b 之前
      }
      if (a > b ) {
        return 1;             // b 會被排列到 a 之前
      }
      // a == b
      return 0;               // a 和 b 的相對位置不變
    }
    
    • 例:數字升序和降序(要比較數字而非字串,比較函式可以簡單的以 a - b)
    // 從小到大,即升序
    var points = [40,100,1,5,25,10];
    points.sort(function(a, b){return a - b});
    // console.log(points);
    // 輸出結果:1,5,10,25,40,100
        
    // 從大到小,即降序
    var points = [40,100,1,5,25,10];
    points.sort(function(a, b){return b - a});
    // console.log(points);
    // 輸出結果:100,40,25,10,5,1
    
  4. Array.prototype.reduce()

    • reduce() 方法接收一個函式作為累加器,陣列中的每個值(從左到右)開始縮減,最終計算為一個值

    • 語法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  5. Array.prototype.includes()

    • 確定陣列中是否包含某個值,並根據需要返回 true 或 false,案例中和 Array.prototype.filter() 配合使用

程式碼展示

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Array Cardio