# 映射

¥Map

通用键到通用值的映射。

¥A mapping of generic keys to generic values.

Map API 与 JavaScript 的 (MDN (opens new window)) 非常相似,但显着的区别是,带有不存在键的 .get 会导致错误,因为无法表示 undefined。示例:

¥The Map API is very similar to JavaScript's (MDN (opens new window)), with the notable difference that a .get with a key that does not exist results in an error, because undefined cannot be represented. Example:

var map = new Map<i32,string>()

// Because `undefined` cannot be represented if a key is not found, this will error:
var str = map.get(1) // ERROR

// The error can be avoided by first making sure that the key exists, so this works:
var str: string | null = map.has(1) ? map.get(1) : null // OK

# 构造函数

¥Constructor

  • new Map<K,V>()
    

    构造一个新的映射,将 K 类型的键映射到 V 类型的值。

    ¥Constructs a new map mapping keys of type K to values of type V.

# 实例成员

¥Instance members

# 字段

¥Fields

  • readonly size: i32
    

    该映射中当前键值对的数量。

    ¥The current number of key-value pairs in this map.

# 方法

¥Methods

  • function clear(): void
    

    清除映射,删除所有键值对。

    ¥Clears the map, deleting all key-value pairs.

  • function delete(key: K): bool
    

    删除对应键的键值对。如果键确实存在,则返回 true,否则返回 false

    ¥Deletes the key-value pair for the corresponding key. Returns true if the key did exist, otherwise false.

  • function get(key: K): V
    

    获取指定 key 对应的 value。如果键不存在则陷阱,因为 "未找到" 无法在所有情况下表示(使用 Map#has 进行检查)。

    ¥Gets the value corresponding to the specified key. Traps if the key does not exist because "not found" cannot be represented in all cases (use Map#has to check).

  • function has(key: K): bool
    

    测试指定的键是否存在。

    ¥Tests if the specified key exists.

  • function keys(): Array<K>
    

    按插入顺序获取此映射中包含的键作为数组。这是初步的,但不支持迭代器。

    ¥Gets the keys contained in this map as an array, in insertion order. This is preliminary while iterators are not supported.

  • function set(key: K, value: V): this
    

    设置指定键的值。如果键不存在,则创建一个新的键值对。

    ¥Sets the value for the specified key. Creates a new key-value pair if the key did not exist.

  • function values(): Array<V>
    

    按插入顺序获取此映射中包含的值作为数组。这是初步的,但不支持迭代器。

    ¥Gets the values contained in this map as an array, in insertion order. This is preliminary while iterators are not supported.

  • function toString(): string
    

    返回此映射的字符串表示形式。

    ¥Returns a string representation of this map.