Skip to content

API HashMap

Liu.Yandong.Hanks edited this page Aug 19, 2026 · 3 revisions

HashMap

键值集合

Key-value collection

脚本 API 目录

概述

HashMap 是面向键查找的集合。基本类型键按值比较,对象键按对象身份比较;没有对应键的 get 返回 null。它适合频繁按键读取的数据,不保证键的遍历顺序。

HashMap is a key-oriented collection. Primitive keys compare by value and object keys by identity; get returns null for a missing key. It is suitable for frequent keyed lookup and does not promise key iteration order.

new HashMap([capacity])

Parameters:

  • capacity
    可选初始容量;只影响预分配,不创建条目。

    Optional initial capacity; affects preallocation only and creates no entries.

Returns

HashMap

Empty HashMap.

var cache = new HashMap(16);
return cache.size; // 0

map.set(key, value)

Parameters:

  • key
    查找键。

    Lookup key.

  • value
    要保存的值。

    Value to store.

Returns

null

null.

用途

新增或覆盖同一键的值。

Adds or replaces a value for the key.

var map = new HashMap();
map.set("theme", "dark");
return map.get("theme");

map.get(key)

Parameters:

  • key
    要读取的键。

    Key to read.

Returns

已保存的值;键不存在时为 null

Stored value, or null when the key is absent.

var map = new HashMap();
map.set("count", 3);
return map.get("count"); // 3

map.getOrInsert(key, valueOrCallback)

Parameters:

  • key
    查找键。

    Lookup key.

  • valueOrCallback
    键缺失时插入的值,或接收该键并产生值的回调。

    Value to insert when absent, or callback that receives the key and produces the value.

Returns

已有值或新插入值。

Existing or newly inserted value.

var cache = new HashMap();
var value = cache.getOrInsert("answer", () => 42);
return value; // 42

map.has(key)

Parameters:

  • key
    要检查的键。

    Key to test.

Returns

键是否存在。

Whether the key exists.

var map = new HashMap();
map.set("ready", true);
return map.has("ready"); // true

map.delete(key)

Parameters:

  • key
    要删除的键。

    Key to remove.

Returns

null

null.

用途

删除键和值;删除不存在的键不会创建条目。

Removes the key and value; removing a missing key does not create an entry.

var map = new HashMap();
map.set("temporary", 1);
map.delete("temporary");
return map.has("temporary"); // false

map.clear()

Parameters:

  • 无。

    None.

Returns

null

null.

var map = new HashMap();
map.set("a", 1);
map.clear();
return map.size; // 0

map.keys

Returns

当前键组成的新数组。

A new array containing current keys.

var map = new HashMap();
map.set("left", 1);
return map.keys[0]; // left

map.values

Returns

当前值组成的新数组。

A new array containing current values.

var map = new HashMap();
map.set("left", 1);
return map.values[0]; // 1

map.size

Returns

当前条目数。

Current entry count.

var map = new HashMap();
map.set("a", 1);
map.set("b", 2);
return map.size; // 2

Clone this wiki locally