JavaScript 中如何将Map键转换为数组
JavaScript 中将 Map 的键转换为数组:
-
调用 Map 上的
keys()
方法以获取包含 Map 中所有键的迭代器对象。 -
调用
Array.from()
方法,将迭代器作为参数传递给它。 Array.from 方法从可迭代对象创建一个新数组。
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
const keys = Array.from(map.keys());
console.log(keys); // 👉️ ['name', 'age']
console.log(keys.length); // 👉️ 2
我们使用 Map.keys
方法获取包含 Map 键的迭代器对象。
我们将迭代器作为唯一参数传递给 Array.from
方法。
Array.from
方法将可迭代对象转换为数组并返回新的数组实例。
这是使用 TypeScript 时推荐的方法,因为编译器在将扩展运算符
(...)
与迭代器一起使用时经常会报错。
另一种方法是使用扩展运算符 ...
。
使用扩展运算符将映射键转换为数组
将 Map 对象的键转换为数组:
-
调用 Map 的
keys()
方法,得到一个包含 Map 的键的迭代器对象。 -
使用展开运算符
...
将迭代器中的值解包到一个新数组中。
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
const keys = [...map.keys()];
console.log(keys); // 👉️ ['name', 'age']
console.log(keys.length); // 👉️ 2
我们使用扩展运算符将 Map 的所有键包含到一个新数组中。
这是将 Map 的键转换为数组时最常用的方法。
我们也可以使用多个map执行此操作。
const map1 = new Map();
map1.set('name', 'John');
map1.set('age', 30);
const map2 = new Map();
map2.set('country', 'Chile');
const keys = [...map1.keys(), ...map2.keys()];
console.log(keys); // 👉️ ['name', 'age', 'country']
console.log(keys.length); // 👉️ 3
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。