js中new Map()的使用方法

1.map的方法及属性

Map对象存有键值对,其中的键可以是任何数据类型。

Map对象记得键的原始插入顺序。

Map对象具有表示映射大小的属性。

1.1 基本的Map() 方法

Method

Description

new Map()

创建新的 Map 对象。

set()

为 Map 对象中的键设置值。

get()

获取 Map 对象中键的值。

entries()

返回 Map 对象中键/值对的数组。

keys()

返回 Map 对象中键的数组。

values()

返回 Map 对象中值的数组。

clear()

删除 Map 中的所有元素。

delete()

删除由键指定的元素。

has()

如果键存在,则返回 true。

forEach()

为每个键/值对调用回调。

1.2 Map()属性

Property

Description

size

获取 Map 对象中某键的值。

2.常用api的使用方法

// 需要的数据
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};

2.1 使用new Map() 创建map对象

// 创建新的 Map
const map = new Map();

2.2 使用set方法 为map对象设置键值对

map.set('name','zhangsan')
//采用键值对的方式,其中name为属性名,zhangsan为属性值

3.使用has方法 判断是否有该属性名

map.has('name') // true
map.has('sex') // false
//如果存在返回true 不存在返回false

4.使用get方法 获取map某个属性的值

map.get('name') // 张三

5.使用delete方法 删除map某个键值对

map.delete('name')

6.使用clear方法 清空map的数据,移除所有元素

map.clear()

7.使用size属性 获取map的长度

map.size()

猜你喜欢

转载自blog.csdn.net/m0_60237095/article/details/129335995