在前端开发中,Map 和 Set 是常用的数据结构之一。ES12 (即 ECMAScript 2021)中,Map 和 Set 也得到了更多的增强和优化。本文将介绍 ES12 中 Map 和 Set 的新方法和语法,并提供实际示例和指导意义。
Map
Map 是一种可以存储键值对的集合。在 ES12 中,Map 有以下新特性:
1. 转换为数组
ES12 中,可以使用 Array.from()
方法将 Map 转换为数组。例如:
const myMap = new Map([ [1, 'one'], [2, 'two'], [3, 'three'] ]); const myArray = Array.from(myMap); console.log(myArray); // [[1, 'one'], [2, 'two'], [3, 'three']]
2. 合并 Map
ES12 中,可以使用 Map.prototype.merge()
方法将两个 Map 合并。如果有相同的键,后面的 Map 中的值会覆盖前面的 Map 中的值。例如:
-- -------------------- ---- ------- ----- ---- - --- ----- --- ------- --- ------ --- ----- ---- - --- ----- --- ---- ------ --- -------- --- ----- --------- - --- ------------- ---------- ----------------------- -- ------ - - -- ------ - -- ---- ----- - -- ------- -展开代码
如果要保留原来的值,可以使用 Map.prototype.setIfAbsent()
方法。例如:
-- -------------------- ---- ------- ----- ---- - --- ----- --- ------- --- ------ --- ----- ---- - --- ----- --- ---- ------ --- -------- --- ----- --------- - --- --------------- --- ------ ----- ------ -- ----- - -------------------------- ------- - ----------------------- -- ------ - - -- ------ - -- ------ - -- ------- -展开代码
3. 遍历键和值
ES12 中,可以使用 Map.prototype.forEach()
方法遍历 Map 中的键和值。例如:
-- -------------------- ---- ------- ----- ----- - --- ----- --- ------- --- ------- --- -------- --- --------------------- ---- -- - ------------------- - ----------- --- -- - - --- -- - - --- -- - - -----展开代码
Set
Set 是一种可以存储唯一值的集合。在 ES12 中,Set 有以下新特性:
1. 转换为数组
ES12 中,可以使用 Array.from()
方法将 Set 转换为数组。例如:
const mySet = new Set(['one', 'two', 'three']); const myArray = Array.from(mySet); console.log(myArray); // ['one', 'two', 'three']
2. 添加多个值
ES12 中,可以使用 Set.prototype.add()
方法添加多个值。例如:
const mySet = new Set(); mySet.add('one', 'two', 'three'); console.log(mySet); // Set(3) { 'one', 'two', 'three' }
3. 遍历值
ES12 中,可以使用 Set.prototype.forEach()
方法遍历 Set 中的值。例如:
const mySet = new Set(['one', 'two', 'three']); mySet.forEach(value => { console.log(value); }); // one // two // three
总结
ES12 中的 Map 和 Set 增加了许多实用的新方法和语法,可以更方便地处理键值对和唯一值的集合。在实际开发中,合理运用这些新特性可以提高代码效率和可读性。
参考资料
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/660a5e91d10417a2229f2e3e