如何在 JavaScript 中创建Map的浅表副本
要创建 Map 的浅表副本,请将现有 Map 作为参数传递给 Map()
构造函数,例如 const newMap = new Map(oldMap)
。 Map()
构造函数接受一个可迭代对象,例如另一个 Map,并将键值对添加到新 Map。
const oldMap = new Map([
['name', 'Tom'],
['country', 'Chile'],
]);
// 👇️ {'name' => 'Tom', 'country' => 'Chile'}
console.log(oldMap);
const copy = new Map(oldMap);
// 👇️ {'name' => 'Tom', 'country' => 'Chile'}
console.log(copy);
我们使用 Map()
构造函数来创建现有 Map 的浅表副本。
构造函数采用的唯一参数是可迭代对象,例如数组或另一个 Map。
iterable
中的元素应该是键值对,例如 二维数组或另一个 Map 对象。
const example1 = [
['name', 'Tom'],
['country', 'Chile'],
];
const example2 = new Map([
['name', 'Tom'],
['country', 'Chile'],
]);
每个键值对都被添加到新地图中。
新的 Map 对象在内存中具有完全不同的引用和位置。 向其添加键值对不会与现有 Map 交互。
const oldMap = new Map([
['name', 'Tom'],
['country', 'Chile'],
]);
// {'name' => 'Tom', 'country' => 'Chile'}
console.log(oldMap);
const copy = new Map(oldMap);
// 👇️ {'name' => 'Tom', 'country' => 'Chile'}
console.log(copy);
copy.set('age', 30);
// 👇️ {'name' => 'Tom', 'country => 'Chile', 'age' => 30}
console.log(copy);
// 👇️ {'name' => 'Tom', 'country => 'Chile'}
console.log(oldMap);
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。