Underscore.js 教學:簡化 JavaScript 陣列與物件操作的輕量函式庫

目次

1. 前言

JavaScript 是 Web 開發中不可或缺的程式語言,但在操作陣列或物件時,程式碼往往容易變得複雜。特別是在資料篩選或轉換等處理上,更需要簡潔高效的寫法。 這時候,「Underscore.js」這個 JavaScript 函式庫就派上用場了。透過這個函式庫,可以將複雜的資料操作寫得更簡單直觀。

Underscore.js 的優勢

  1. 程式碼簡化
  • 傳統 JavaScript 中容易冗長的處理,使用 Underscore.js 只需幾行即可完成。
  1. 內建多樣化函數
  • 提供了豐富的功能,例如陣列操作、物件處理、函數控制等。
  1. 輕量且靈活
  • 可直接使用所需函數,對效能的影響降到最低。

本文將學到什麼

  • 如何導入 Underscore.js
  • 基礎函數與應用範例
  • 在實際開發中的使用案例

2. 什麼是 Underscore.js

Underscore.js 概述

Underscore.js 是一個輕量級函式庫,能夠簡化 JavaScript 中的資料操作。它提供了眾多方便的函數,專門用來提升陣列和物件的操作效率,因此也被稱為 JavaScript 的輔助工具包。 雖然 JavaScript 本身已具備強大的操作能力,但往往會導致程式碼過長或可讀性下降。透過使用 Underscore.js,可以解決這些問題,撰寫更簡潔且易於維護的程式碼。

主要特點

  1. 豐富的工具函數
  • 提供陣列操作物件操作函數控制等多種函數。
  1. 簡潔且可讀性高
  • 相較於傳統 JavaScript,能用更少的程式碼達到相同功能。
  1. 無相依性
  • 不依賴其他函式庫,能靈活整合於各種專案。
  1. 輕量且高速
  • 檔案體積小,對效能影響低,非常適合現代 Web 應用。

Underscore.js 與 Lodash 的比較

與 Underscore.js 常被比較的函式庫是「Lodash」。Lodash 基於 Underscore.js 發展,並進一步加強了功能,兩者的差異如下:
特點Underscore.jsLodash
功能性提供基本的工具函數功能更全面,涵蓋更多情境
模組化支援部分支援完整模組化
效能快速更快,並針對效能最佳化
選擇哪一個取決於專案需求:若需要簡單且輕量的函式庫,Underscore.js 更合適;若專案需要更多功能與最佳化,Lodash 可能更適用。

Underscore.js 如何發揮作用?

Underscore.js 在以下情境中特別有用:
  1. 陣列資料操作
  • 例如資料篩選、映射等操作,可以用簡潔的語法完成。
  1. 物件操作
  • 方便取得物件的鍵與值,或進行合併處理。
  1. 函數控制
  • 支援一次性執行、延遲執行等控制方式,讓邏輯更清晰。
  1. 工具函數活用
  • 提供排序、隨機化,甚至能當作簡易模板引擎使用。

3. 導入方式

本節將介紹將 Underscore.js 加入專案的具體方法,包括透過 CDN、npm 或 yarn 安裝,以及直接下載檔案使用。

1. 使用 CDN

CDN(內容傳遞網路)讓你只需在 HTML 中引入連結即可使用。將以下程式碼加入 <head><body> 標籤中:

範例:加入 HTML

<!DOCTYPE html>
<html lang="zh-TW">
<head>
  <meta charset="UTF-8">
  <title>Underscore.js 導入</title>
  <!-- Underscore.js CDN 連結 -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
</head>
<body>
  <h1>Underscore.js 測試</h1>
  <script>
    // 測試程式
    const data = [1, 2, 3, 4, 5];
    const evenNumbers = _.filter(data, function(num) {
      return num % 2 === 0;
    });
    console.log(evenNumbers); // [2, 4]
  </script>
</body>
</html>
開啟後,可以在瀏覽器的開發者工具主控台中看到只顯示偶數。

2. 使用 npm 或 yarn 安裝

如果是 Node.js 或本地開發環境,可以用 npm 或 yarn 安裝。

npm 安裝

npm install underscore

yarn 安裝

yarn add underscore

在 JavaScript 中匯入

import _ from 'underscore';

const data = [10, 20, 30, 40];
const result = _.map(data, (num) => num * 2);
console.log(result); // [20, 40, 60, 80]

3. 下載檔案使用

  1. 進入官方網站(underscorejs.org)。
  2. 從「Download」區塊下載最新版的 JS 檔案。
  3. 將檔案放到專案資料夾(例如 js/)。
  4. 在 HTML 中以 script 標籤引入。
<script src="js/underscore-min.js"></script>

4. 使用模組打包工具

若使用 Webpack 或 Parcel 也能輕鬆整合。

Webpack 範例

  1. 安裝:npm install underscore
  2. 在程式中匯入:
    import _ from 'underscore';
  3. 即可打包使用。

常見問題排解

1. 出現 “Uncaught ReferenceError: _ is not defined”
  • 檢查是否正確引入 CDN 或 import 路徑。
2. npm 安裝後出現錯誤
  • 請確認 Node.js 與 npm 版本為最新。

4. 基本用法

本節將介紹 Underscore.js 的基礎函數與範例,這些函數能大幅提升操作陣列與物件的效率。

1. 陣列迭代處理 – _.each()

_.each() 用於迭代陣列或物件。

範例

const numbers = [1, 2, 3, 4, 5];

// 輸出每個元素
_.each(numbers, function(num) {
  console.log(num);
});
輸出結果:
1  
2  
3  
4  
5
重點:
  • 可應用於陣列與物件。
  • 回呼函數會接收元素、索引與整個集合。

2. 陣列映射 – _.map()

_.map() 對陣列每個元素套用函數,回傳新陣列。

範例

const numbers = [1, 2, 3, 4, 5];

// 將元素乘以 2
const doubled = _.map(numbers, function(num) {
  return num * 2;
});

console.log(doubled);
輸出結果:
[2, 4, 6, 8, 10]

3. 找到符合條件的第一個元素 – _.find()

_.find() 回傳符合條件的第一個元素。

範例

const numbers = [1, 2, 3, 4, 5];

// 找到大於等於 3 的第一個元素
const result = _.find(numbers, function(num) {
  return num >= 3;
});

console.log(result);
輸出結果:
3

4. 篩選所有符合條件的元素 – _.filter()

_.filter() 會回傳符合條件的所有元素。

範例

const numbers = [1, 2, 3, 4, 5];

// 篩選偶數
const evens = _.filter(numbers, function(num) {
  return num % 2 === 0;
});

console.log(evens);
輸出結果:
[2, 4]

5. 打亂陣列元素 – _.shuffle()

_.shuffle() 會隨機重新排列陣列。

範例

const numbers = [1, 2, 3, 4, 5];

const shuffled = _.shuffle(numbers);
console.log(shuffled);
輸出結果:(範例)
[3, 5, 1, 4, 2]

6. 移除重複元素 – _.uniq()

_.uniq() 移除陣列中的重複值。

範例

const numbers = [1, 2, 2, 3, 4, 4, 5];

const uniqueNumbers = _.uniq(numbers);
console.log(uniqueNumbers);
輸出結果:
[1, 2, 3, 4, 5]

小結

本節介紹了 Underscore.js 的基礎函數與範例:
  • _.each():迭代元素
  • _.map():產生新陣列
  • _.find()_.filter():查找或篩選元素
  • _.shuffle():隨機排序
  • _.uniq():移除重複值

5. 進階用法

本節將介紹 Underscore.js 的進階函數與應用範例,透過這些功能可以進行更高階的資料操作與分析。

1. 陣列排序 – _.sortBy()

_.sortBy() 可根據指定的鍵或條件對陣列進行排序。

範例

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 20 },
  { name: 'Charlie', age: 30 }
];

// 依照年齡排序
const sortedUsers = _.sortBy(users, 'age');

console.log(sortedUsers);
輸出結果:
[
  { name: 'Bob', age: 20 },
  { name: 'Alice', age: 25 },
  { name: 'Charlie', age: 30 }
]

2. 陣列分組 – _.groupBy()

_.groupBy() 會依照指定的條件對元素進行分組。

範例

const numbers = [1.1, 2.3, 2.4, 3.5, 4.7];

// 依照整數部分分組
const grouped = _.groupBy(numbers, function(num) {
  return Math.floor(num);
});

console.log(grouped);
輸出結果:
{
  1: [1.1],
  2: [2.3, 2.4],
  3: [3.5],
  4: [4.7]
}

3. 資料統計 – _.countBy()

_.countBy() 可快速進行資料統計。

範例

const words = ['apple', 'banana', 'apricot', 'blueberry'];

// 依照單字首字母分類並計算數量
const counts = _.countBy(words, function(word) {
  return word[0];
});

console.log(counts);
輸出結果:
{
  a: 2,
  b: 2
}

小結

本節介紹了 Underscore.js 的進階用法:
  • _.sortBy():排序陣列
  • _.groupBy()_.countBy():分組與統計資料

6. 物件操作

本節將介紹使用 Underscore.js 操作物件的常用函數,這些方法能有效處理物件的屬性與值。

1. 取得物件的鍵與值

取得鍵 – _.keys()

const person = { name: 'Alice', age: 25, city: 'Tokyo' };

const keys = _.keys(person);
console.log(keys);
輸出結果:
['name', 'age', 'city']

取得值 – _.values()

const values = _.values(person);
console.log(values);
輸出結果:
['Alice', 25, 'Tokyo']

2. 建立物件的複製 – _.clone()

_.clone() 會建立淺層複製,保留原始物件不受影響。
const original = { name: 'Alice', age: 25 };
const clone = _.clone(original);

clone.age = 30; // 修改複製品
console.log(original.age); // 25
console.log(clone.age);    // 30

小結

本節介紹了 Underscore.js 在物件操作上的應用:
  • _.keys()_.values():取得物件的鍵與值
  • _.clone():建立物件的複製

7. 函數操作

本節將介紹如何使用 Underscore.js 來有效控制函數的執行,這些功能有助於優化效能與管理邏輯。

1. 綁定函數 – _.bind()

_.bind() 可在執行函數時,將 this 綁定到指定物件。

範例

const person = {
  name: 'Alice',
  greet: function(greeting) {
    return `${greeting}, my name is ${this.name}`;
  }
};

const boundGreet = _.bind(person.greet, person);
console.log(boundGreet('Hello')); // Hello, my name is Alice

2. 延遲執行 – _.delay()

_.delay() 可以讓函數延遲一段時間後再執行。

範例

_.delay(function(message) {
  console.log(message);
}, 2000, '2 秒後顯示');
輸出結果:(2 秒後)
2 秒後顯示

3. 僅執行一次 – _.once()

_.once() 保證函數只會執行一次,之後的呼叫會被忽略。

範例

const initialize = _.once(function() {
  console.log('初始化完成');
});

initialize(); // 執行
initialize(); // 忽略

4. 記憶化函數 – _.memoize()

_.memoize() 會快取函數結果,當相同參數再次呼叫時,直接回傳快取值。

範例

const factorial = _.memoize(function(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
});

console.log(factorial(5)); // 計算
console.log(factorial(5)); // 使用快取

5. 節流控制 – _.throttle()

_.throttle() 可控制函數在固定時間間隔內只執行一次。

範例

const log = _.throttle(function() {
  console.log('執行中...');
}, 2000);

// 模擬快速觸發事件
setInterval(log, 500); // 每 2 秒只執行一次

小結

本節介紹了 Underscore.js 在函數操作上的應用:
  • _.bind():固定 this
  • _.delay():延遲執行
  • _.once():僅執行一次
  • _.memoize():快取函數結果
  • _.throttle():最佳化執行頻率

8. 實用工具函數

本節將介紹 Underscore.js 的實用工具函數,這些功能在資料處理、隨機生成以及模板應用上非常有幫助。

1. 生成隨機數值 – _.random()

_.random() 可以生成指定範圍內的隨機整數或小數。

範例

console.log(_.random(1, 10)); // 整數
console.log(_.random(1, 10, true)); // 含小數

2. 檢查是否為空 – _.isEmpty()

_.isEmpty() 可判斷陣列、物件或字串是否為空。

範例

console.log(_.isEmpty([]));        // true
console.log(_.isEmpty({}));        // true
console.log(_.isEmpty(''));        // true
console.log(_.isEmpty([1, 2, 3])); // false

3. 建立模板 – _.template()

_.template() 用於建立字串模板,並可動態插入資料。

範例

const template = _.template('你好,<%= name %>!');
console.log(template({ name: 'Alice' }));
輸出結果:
你好,Alice!

小結

本節介紹了 Underscore.js 的實用工具函數:
  • _.random():生成隨機數值
  • _.isEmpty():檢查資料是否為空
  • _.template():建立模板引擎

9. 總結

本文詳細介紹了 Underscore.js 的基礎與進階用法。這個函式庫能讓 JavaScript 的資料操作更簡單、更高效,是開發中非常實用的工具。

回顧內容

  1. 基礎用法 – 學習了操作陣列與物件的基本函數。
  2. 進階用法 – 掌握了分類、排序與統計等進階操作。
  3. 函數操作 – 理解了執行控制與快取等最佳化方法。
  4. 工具函數 – 熟悉了隨機數生成、資料檢查與模板應用。

結語

Underscore.js 是一個強大的工具,能讓 JavaScript 開發更高效、更易於維護。建議在專案中嘗試應用,透過實踐來提升開發技能。

常見問題(FAQ)

Q1: Underscore.js 可以免費使用嗎?

A: 可以。它採用 MIT 授權,商業專案也能免費使用。

Q2: Underscore.js 和 Lodash 有什麼不同?

A: Underscore.js 輕量且簡單,而 Lodash 基於它進一步擴展,具備更佳效能與模組化設計。選擇取決於專案需求。

Q3: 在 ES6+ 之後還需要 Underscore.js 嗎?

A: ES6+ 已內建許多陣列與物件操作方法,但 Underscore.js 在跨瀏覽器相容性、程式簡化以及維護舊專案時仍然有用。

Q4: 適合哪些專案使用 Underscore.js?

A: 特別適合中小型專案,或在需要快速完成資料操作時。若追求輕量化,它是理想選擇。

Q5: 如何安裝 Underscore.js?

A: 有三種方式:
  1. 使用 CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
  1. 使用 npm:
npm install underscore
  1. 使用 yarn:
yarn add underscore

Q6: 官方文件在哪裡可以查到?

A: 官方文件可在 Underscore.js 官方網站 查閱。

Q7: 適合大型專案嗎?

A: 可以,但對於大型專案,通常會推薦使用功能更完整的 Lodash。不過若追求輕量,Underscore.js 依舊合適。

Q8: 函數執行控制是否有其他方式?

A: 當然可以。原生 JavaScript 提供 setTimeout()setInterval()Promiseasync/await 等。但 _.throttle()_.debounce() 可讓程式更簡潔。

Q9: 使用時有哪些注意事項?

A:
  1. 避免過度依賴,因為 ES6+ 已支援許多功能。
  2. 請確保使用最新版本以降低安全風險。
  3. 專案規模較大時可考慮轉向 Lodash。

Q10: 適合作為模板引擎嗎?

A: _.template() 適合簡單模板處理,但若需要更強大的功能,建議使用 Handlebars.js 或 EJS。
広告