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 的对比

经常被拿来比较的库是 Lodash。Lodash 在 Underscore.js 的基础上进行了功能扩展,两者的差异如下所示。

AspectUnderscore.jsLodash
FunctionalityIncludes many core utility functionsOffers an even broader feature set
Modular usagePartially supportedFully modularized
PerformanceFastFast and further optimized

选择哪一个取决于项目需求,但如果你想要一个简洁轻量的库,Underscore.js 是一个强有力的选项。

Underscore.js 能帮你做什么?

Underscore.js 在以下场景中特别有用。

  1. 数组数据操作
  • 为过滤、映射等操作提供简洁的代码实现。
  1. 对象操作
  • 轻松获取键/值、合并元素等任务。
  1. 函数控制
  • 简单实现 “只运行一次” 或延迟执行等控制逻辑。
  1. 利用实用助手
  • 还能用于排序、随机化,甚至充当简易的模板引擎。

3. 安装

本节将手把手演示如何将 Underscore.js 添加到项目中。你将学习通过 CDN 引入以及本地下载文件进行安装的两种方式。

1. 使用 CDN

CDN(内容分发网络)是一种通过链接互联网上托管的文件即可使用库的便捷方式。你可以在 HTML 文件的 <head> 标签内或 <body> 标签末尾添加以下代码来使用 Underscore.js。

示例:在 HTML 文件中引入

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Underscore.js 示例</title>
    <!-- CDN 引入 Underscore.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.7/underscore-min.js"></script>
</head>
<body>
    <script>
        // 使用 Underscore.js 的示例代码
        const numbers = [1, 2, 3, 4, 5];
        const evens = _.filter(numbers, n => n % 2 === 0);
        console.log('偶数数组:', evens);
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="ja">
<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 安装

通过 npm 或 yarn,您也可以在本地环境或 Node.js 项目中使用 Underscore.js。

使用 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” 部分下载最新的 JavaScript 文件。
  3. 将下载的文件放置在项目中的合适文件夹(例如 js/)。
  4. 在 HTML 文件中使用 <script> 标签引入它。
    <script src="js/underscore-min.js"></script>
    

4. 使用模块打包工具时

如果您使用 Webpack、Parcel 等模块打包工具,也可以轻松集成 Underscore.js。

示例:Webpack 配置

  1. 使用 npm 安装它。
    npm install underscore
    
  1. 在您的 JavaScript 文件中导入它。
    import _ from 'underscore';
    
  1. 根据需要进行打包并在项目中使用它。

故障排除

1. 如果看到 “Uncaught ReferenceError: _ is not defined”

  • Underscore.js 可能未正确加载。请再次检查您的 CDN 链接或导入路径。

2. 如果在使用 npm 安装后出现错误

  • 将 Node.js 和 npm 更新到最新版本。

4. 基本用法

在本节中,我们将介绍 Underscore.js 的一些核心函数及其实用示例。这些函数在高效处理数组和对象时非常有用。

1. 遍历数组 – _.each()

_.each() 是用于遍历数组或对象的函数。

示例

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

// Output each element to the console
_.each(numbers, function(num) {
  console.log(num);
});

输出:

1  
2  
3  
4  
5

关键点:

  • 它不仅适用于数组,也适用于对象。
  • 回调函数会接收元素、本身的索引以及整个集合。

2. 映射数组 – _.map()

_.map() 将函数应用于数组的每个元素,并返回一个新数组。

示例

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

// Double each element
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];

// Find the first element greater than or equal to 3
const result = _.find(numbers, function(num) {
  return num >= 3;
});

console.log(result);

输出:

3

4. 过滤所有匹配元素 – _.filter()

_.filter() 提取所有满足条件的元素,并以新数组返回它们。

示例

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

// Extract only even numbers
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];

// Randomly shuffle the array
const shuffled = _.shuffle(numbers);

console.log(shuffled);

输出: (示例)

[3, 5, 1, 4, 2]

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

_.uniq() 从数组中移除重复值。

示例

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

// Remove duplicate elements
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 }
];

// Sort by age
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];

// Group by integer part
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'];

// Count by first letter
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; // Modify the clone
console.log(original.age); // 25
console.log(clone.age);    // 30

总结

在本节中,我们解释了如何使用 Underscore.js 处理对象。

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, 'Displayed after 2 seconds');

输出:(2 秒后)

Displayed after 2 seconds

3. 只执行一次 – _.once()

_.once() 确保函数只被执行一次,后续的调用会被忽略。

示例

const initialize = _.once(function() {
  console.log('Initialization complete');
});

initialize(); // Executed
initialize(); // Ignored

4. 记忆化 – _.memoize()

_.memoize() 缓存函数的返回结果,当使用相同参数再次调用时直接返回缓存,避免重新计算。

示例

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

console.log(factorial(5)); // Calculated
console.log(factorial(5)); // Retrieved from cache

5. 节流函数执行 – _.throttle()

_.throttle() 限制函数的执行频率,防止在短时间内被频繁调用。

示例

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

// Simulate continuous events
setInterval(log, 500); // Executes only once every 2 seconds

小结

在本节中,我们探讨了 Underscore.js 中与函数相关的实用工具。

  • _.bind() 用于固定 this 上下文
  • _.delay() 用于延迟执行
  • _.once() 用于一次性执行
  • _.memoize() 用于缓存结果
  • _.throttle() 用于优化执行频率

8. 实用函数

在本节中,我们将介绍 Underscore.js 提供的便利实用函数。这些函数在数据处理、随机生成以及模板渲染等多种场景中都非常有用。

1. 生成随机数 – _.random()

_.random() 在指定范围内生成随机整数或浮点数。

示例

console.log(_.random(1, 10)); // Integer
console.log(_.random(1, 10, true)); // Floating-point

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('Hello, <%= name %>!');
console.log(template({ name: 'Alice' }));

输出:

Hello, Alice!

小结

在本节中,我们介绍了 Underscore.js 的实用函数。

  • _.random() 用于生成随机数
  • _.isEmpty() 用于检查数据状态
  • _.template() 用于简易模板渲染

9. 结论

本文从基础用法到进阶技巧全面讲解了 Underscore.js。该库在简化 JavaScript 数据操作、编写高效且易维护的代码方面极为有用。

关键要点

  1. 基础用法 – 学习了数组和对象操作的核心函数。
  2. 进阶用法 – 探索了分组、排序和聚合。
  3. 函数工具 – 覆盖了执行控制和记忆化。
  4. 实用助手 – 介绍了随机生成和模板渲染。

最后思考

Underscore.js 是一款强大的工具,能够让 JavaScript 开发更加高效、易上手。将本文作为参考,在自己的项目中尝试使用它。持续的动手实践将帮助你进一步提升技能。

常见问题 (FAQ)

Q1:Underscore.js 是否免费使用?

A: 是的。Underscore.js 在 MIT 许可证下发布,可免费使用,包括在商业项目中。

Q2:Underscore.js 与 Lodash 有何区别?

A: Underscore.js 是一个简单且轻量的实用工具库。Lodash 在 Underscore.js 的基础上增加了更多功能、性能优化以及更强的模块化。可根据项目需求进行选择。

Q3:在现代 JavaScript(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:Underscore.js 能用于大规模项目吗?

A: 可以。但对于大型项目,通常推荐使用 Lodash,因为它的模块化结构和额外的优化更适合。Underscore.js 仍然是轻量使用场景的理想选择。

Q8:有没有函数执行控制的替代方案?

A: 有。现代 JavaScript 提供了 setTimeout()setInterval()Promiseasync/await 等替代方案。不过,Underscore.js 的 _.throttle()_.debounce() 能让实现更简洁、更易读。

Q9:使用 Underscore.js 时有哪些注意事项?

A:

  1. 当原生 JavaScript 功能足够时,避免不必要的依赖。
  2. 保持版本更新,以降低安全风险。
  3. 根据项目规模考虑是否迁移到 Lodash。

Q10:Underscore.js 适合作为模板引擎吗?

A: _.template() 适用于简单的场景,但对于更复杂的模板需求,建议使用专门的库,如 Handlebars.js 或 EJS。

広告