JavaScript标准对象:地图

本文深入解析JavaScript中的Map对象,一种按插入顺序保存键值对的标准内置对象。文章详细介绍了Map对象的创建、常用方法如get、set、size、entries等的使用,以及如何通过现有数组或对象创建Map。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Map object is a relatively new standard built-in object that holds [key, value] pairs in the order that they're inserted.

Map对象是一个相对较新的标准内置对象,按插入顺序保存[key, value]对。

The keys and values in the Map object can be any value (both objects and primitive values are valid).

Map对象中的键和值可以是任何值(对象和基本值均有效)。

句法 (Syntax)

new Map([iterable])

参量 (Parameters)

iterable An Array or other iterable object whose elements are key-value pairs.

iterable一个数组或其他可迭代对象,其元素为键值对。

(Example)

const myMap = new Map();
myMap.set('foo', 1);
myMap.set('bar', 2);
myMap.set('baz', 3);

myMap.get('foo');   // returns 1
myMap.get('baz');   // returns 3
myMap.get('hihi');  // return undefined

myMap.size;   // 3

console.log(myMap); // Map { 'foo' => 1, 'bar' => 2, 'baz' => 3 }

It's easy to create a new Map from existing 2D arrays of key-value pairs:

根据现有的键值对的2D数组创建新的Map很容易:

const myArr = [['foo', 1], ['bar', 2], ['baz', 3]];
const arrMap = new Map(myArr);

console.log(arrMap); // Map { 'foo' => 1, 'bar' => 2, 'baz' => 3 }

You can also convert an object into a Map with the help of the Object.entries:

您还可以借助Object.entries将对象转换为Map

const myObj = {
  foo: 1,
  bar: 2,
  baz: 3
}
const objMap = new Map(Object.entries(myObj));

console.log(objMap); // Map { 'foo' => 1, 'bar' => 2, 'baz' => 3 }

Map.prototype.get (Map.prototype.get)

Returns the value of the specified key from a Map object.

Map对象返回指定键的值。

句法 (Syntax)

myMap.get(key);

参量 (Parameters)

key Required.

密钥必填。

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);

myMap.get('foo');   // returns 1
myMap.get('baz');   // returns 3
myMap.get('hihi');  // return undefined

Map.prototype.set (Map.prototype.set)

Sets or updates an element with the specified key and value in a Map object. The set() method also returns the Map object.

使用Map对象中的指定键和值设置或更新元素。 set()方法还返回Map对象。

句法 (Syntax)

myMap.set(key, value);

参量 (Parameters)

  • key Required

    key

  • value Required

    需要的

(Example)

const myMap = new Map();

// sets new elements
myMap.set('foo', 1);
myMap.set('bar', 2);
myMap.set('baz', 3);

// Updates an existing element
myMap.set('foo', 100);

myMap.get('foo');   // returns 100

Because set() returns the Map object it operated on, the method can be easily chained. For example, the code above can be simplified to:

由于set()返回对其进行操作的Map对象,因此可以轻松地链接该方法。 例如,上面的代码可以简化为:

const myMap = new Map();

// sets new elements
myMap.set('foo', 1)
  .set('bar', 2)
  .set('baz', 3)
  .set('foo', 100); // Updates an existing element

myMap.get('foo');   // returns 100

Map.prototype.size (Map.prototype.size)

Returns the number of elements in a Map object.

返回Map对象中的元素数。

句法 (Syntax)

myMap.size();

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


myMap.size(); // 3

Map.prototype.keys (Map.prototype.keys)

Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

返回一个新的Iterator对象,该对象按插入顺序包含Map对象中每个元素的键。

句法 (Syntax)

myMap.keys()

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


const iterator = myMap.keys();

console.log(iterator.next().value); // 'foo'
console.log(iterator.next().value); // 'bar'
console.log(iterator.next().value); // 'baz'

Map.prototype.values (Map.prototype.values)

Returns an iterator object that contains the values for each element in the Map object in the order they were inserted.

返回一个迭代器对象,该迭代器对象按插入顺序包含Map对象中每个元素的值。

句法 (Syntax)

myMap.values()

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


const iterator = myMap.values();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3

Map.prototype.delete (Map.prototype.delete)

Removes the specified element from a Map object. Returns whether the key was found and successfully deleted.

Map对象移除指定的元素。 返回是否找到并成功删除密钥。

句法 (Syntax)

myMap.delete(key);

参量 (Parameters)

key Required.

密钥必填。

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


myMap.size(); // 3
myMap.has('foo'); // true;

myMap.delete('foo');  // Returns true. Successfully removed.

myMap.size(); // 2
myMap.has('foo');    // Returns false. The "foo" element is no longer present.

Map.prototype.entries (Map.prototype.entries)

Returns a new Iterator object that contains the [key, value] pairs for each element in the Map object in insertion order.

返回一个新的Iterator对象,该对象包含按插入顺序的Map对象中每个元素的[key, value]对。

句法 (Syntax)

myMap.entries()

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


const iterator = myMap.entries();

console.log(iterator.next().value); // ['foo', 1]
console.log(iterator.next().value); // ['bar', 2]
console.log(iterator.next().value); // ['baz', 3]

Map.prototype.clear (Map.prototype.clear)

Removes all elements from a Map object and returns undefined.

Map对象移除所有元素,并返回undefined

句法 (Syntax)

myMap.clear();

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);


myMap.size(); // 3
myMap.has('foo'); // true;

myMap.clear(); 

myMap.size(); // 0
myMap.has('foo'); // false

Map.prototype.has (Map.prototype.has)

Given a Map with elements inside, the has() function allows you to determine whether or not an element exists inside the Map, based on a key that you pass.

给定一个Map内部包含元素, has()函数允许您根据传递的键来确定Map中是否存在元素。

The has() function returns a Boolean primitive (either true or false), which indicates that the Map contains the element or not.

has()函数返回一个Boolean原语 ( truefalse ),它指示Map是否包含该元素。

You pass a key parameter to the has() function, which will be used to look for an element with that key inside the Map.

您将key参数传递给has()函数,该函数将用于在Map中查找具有该键的元素。

Example:

例:

// A simple Map
const campers = new Map();

// add some elements to the map
// each element's key is 'camp' and a number
campers.set('camp1', 'Bernardo');
campers.set('camp2', 'Andrea');
campers.set('camp3', 'Miguel');

// Now I want to know if there's an element
// with 'camp4' key:
campers.has('camp4');
// output is `false`

The campers Map does not currently have an element with a 'camp4' key. Therefore, the has('camp4') function call will return false.

campers地图当前没有带有'camp4'键的元素。 因此, has('camp4')函数调用将返回false

// If we add an element with the 'camp4' key to the map
campers.set('camp4', 'Ana');

// and try looking for that key again
campers.has('camp4');
// output is `true`

Since the map now does have an element with a 'camp4' key, the has('camp4') function call will return true this time!

由于地图现在确实具有带有'camp4'键的元素,因此has('camp4')函数调用这次将返回true

In a more real-world scenario, you might not manually add the elements to the Map yourself, so the has() function would become really useful in those cases.

在更真实的场景中,您可能不会自己手动将元素添加到Map中,因此has()函数在这些情况下将非常有用。

Map.prototype.forEach (Map.prototype.forEach)

Executes the passed function on each key-value pair in the Map object. Returns undefined.

Map对象中的每个键值对上执行传递的函数。 返回undefined

句法 (Syntax)

myMap.forEach(callback, thisArg)

参量 (Parameters)

  • callback Function to execute for each element.

    callback为每个元素执行的功能。

  • thisArg Value to use as this when executing callback.

    thisArg在执行回调时用作此值。

(Example)

const myMap = new Map();
myMap.set('foo',1);
myMap.set('bar',2);
myMap.set('baz',3);

function valueLogger(value) {
  console.log(`${value}`);
}

myMap.forEach(valueLogger);
// 1
// 2
// 3

翻译自: https://www.freecodecamp.org/news/javascript-standard-objects-maps/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值