」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在JavaScript中設置VS數組:何時使用哪個?

在JavaScript中設置VS數組:何時使用哪個?

發佈於2025-02-19
瀏覽:347

Set vs Array in JavaScript: When to Use Which?

JavaScript 提供了兩種強大的數據結構用於存儲集合:SetArray。雖然兩者都可以存儲多個值,但它們獨特的特性使得它們更適合不同的場景。讓我們探討何時以及為何選擇其中一個而不是另一個。

  1. 默認情況下唯一的值

Set 最顯著的特徵是其自動處理重複項。

// 数组允许重复
const arr = [1, 2, 2, 3, 3, 4];
console.log(arr); // [1, 2, 2, 3, 3, 4]

// Set 自动删除重复项
const set = new Set([1, 2, 2, 3, 3, 4]);
console.log([...set]); // [1, 2, 3, 4]

// 使用 Set 从数组中删除重复项
const uniqueArray = [...new Set(arr)];
console.log(uniqueArray); // [1, 2, 3, 4]
  1. 元素檢查性能

Set 提供了更快的查找時間來檢查元素是否存在。

const largeArray = Array.from({ length: 1000000 }, (_, i) => i);
const largeSet = new Set(largeArray);

// 数组查找
console.time('Array includes');
console.log(largeArray.includes(999999));
console.timeEnd('Array includes');

// Set 查找
console.time('Set has');
console.log(largeSet.has(999999));
console.timeEnd('Set has');

// Set 明显更快,因为它内部使用哈希表
  1. 可用的方法和操作

Array 提供了更多用於數據操作的內置方法,而 Set 專注於唯一性管理。

// 数组方法
const arr = [1, 2, 3, 4, 5];
arr.push(6);                    // 添加到末尾
arr.pop();                      // 从末尾移除
arr.unshift(0);                 // 添加到开头
arr.shift();                    // 从开头移除
arr.splice(2, 1, 'new');       // 替换元素
arr.slice(1, 3);               // 提取部分
arr.map(x => x * 2);           // 转换元素
arr.filter(x => x > 2);        // 过滤元素
arr.reduce((a, b) => a   b);   // 归约为单个值

// Set 方法
const set = new Set([1, 2, 3, 4, 5]);
set.add(6);                    // 添加值
set.delete(6);                 // 删除值
set.has(5);                    // 检查是否存在
set.clear();                   // 删除所有值
  1. 順序和索引訪問

Array 保持插入順序並提供基於索引的訪問,而 Set 只保持插入順序。

// 数组索引访问
const arr = ['a', 'b', 'c'];
console.log(arr[0]);      // 'a'
console.log(arr[1]);      // 'b'
arr[1] = 'x';            // 直接修改

// Set 没有索引访问
const set = new Set(['a', 'b', 'c']);
console.log([...set][0]); // 需要先转换为数组
// 不允许直接修改索引
  1. 內存使用

Set 通常比 Array 使用更多內存,但提供更快的查找。

// 内存比较(粗略示例)
const numbers = Array.from({ length: 1000 }, (_, i) => i);

// 数组内存
const arr = [...numbers];
console.log(process.memoryUsage().heapUsed);

// Set 内存
const set = new Set(numbers);
console.log(process.memoryUsage().heapUsed);
// 由于哈希表结构,Set 通常使用更多内存
  1. 常用用例

何時使用數組:

// 1. 当顺序和索引访问很重要时
const playlist = ['song1.mp3', 'song2.mp3', 'song3.mp3'];
const currentTrack = playlist[currentIndex];

// 2. 当您需要数组方法时
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(x => x * 2);
const sum = numbers.reduce((a, b) => a   b, 0);

// 3. 当重复值可以接受或需要时
const votes = ['yes', 'no', 'yes', 'yes', 'no'];
const yesVotes = votes.filter(vote => vote === 'yes').length;

何時使用 Set:

// 1. 当跟踪唯一值时
const uniqueVisitors = new Set();
function logVisitor(userId) {
    uniqueVisitors.add(userId);
    console.log(`Total unique visitors: ${uniqueVisitors.size}`);
}

// 2. 用于快速查找操作
const allowedUsers = new Set(['user1', 'user2', 'user3']);
function checkAccess(userId) {
    return allowedUsers.has(userId);
}

// 3. 用于删除重复项
function getUniqueHashtags(posts) {
    const uniqueTags = new Set();
    posts.forEach(post => {
        post.hashtags.forEach(tag => uniqueTags.add(tag));
    });
    return [...uniqueTags];
}

在 Set 和數組之間轉換

您可以根據需要輕鬆地在 SetArray 之間轉換。

// 数组到 Set
const arr = [1, 2, 2, 3, 3, 4];
const set = new Set(arr);

// Set 到数组 - 三种方法
const back1 = [...set];
const back2 = Array.from(set);
const back3 = Array.from(set.values());

// 用于数组去重
const deduped = [...new Set(arr)];

結論

當您需要以下情況時,選擇 Array

  • 基於索引的訪問
  • 廣泛的數組方法(map、reduce、filter 等)
  • 重複值
  • 內存效率
  • 傳統迭代模式

當您需要以下情況時,選擇 Set

  • 僅唯一值
  • 快速查找操作
  • 簡單添加/刪除操作
  • 保持唯一項目列表
  • 快速去重

請記住,您可以隨時在兩種類型之間進行轉換,因此請選擇最適合您當前需求的一種。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3