温馨提示×

JavaScript Map get()实例讲解

小亿
92
2023-12-18 16:47:54
栏目: 编程语言

Map get() 方法用于获取指定键对应的值。以下是一个使用 get() 方法的示例:

let map = new Map();
map.set('name', 'John');
map.set('age', 30);

let name = map.get('name');
console.log(name); // 输出:John

let age = map.get('age');
console.log(age); // 输出:30

在上面的示例中,我们创建了一个 Map 对象,并使用 set() 方法向其中添加了两个键值对。然后,通过 get() 方法获取了指定键的值,并将其打印到控制台上。

注意,如果指定的键不存在于 Map 对象中,get() 方法将返回 undefined。因此,在使用 get() 方法之前,最好先使用 has() 方法检查一下指定的键是否存在。

let map = new Map();
map.set('name', 'John');
map.set('age', 30);

if (map.has('name')) {
  let name = map.get('name');
  console.log(name); // 输出:John
}

if (map.has('country')) {
  let country = map.get('country');
  console.log(country);
} else {
  console.log('country 不存在于 Map 对象中');
}

以上代码中,我们首先使用 has() 方法检查了指定的键是否存在于 Map 对象中。然后,根据检查结果,使用 get() 方法获取了对应的值,并打印到控制台上。如果键不存在,则打印一条提示信息。

总结一下,通过使用 Map 对象的 get() 方法,我们可以根据键获取到对应的值。如果键不存在,则返回 undefined。在使用 get() 方法之前,最好先使用 has() 方法检查一下键是否存在。

0