Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Object Methods

A key in brackets is computed: its value, a string, is the key.

fun counter(name) { return { [name]: 0, [name + "Max"]: 10 }; }
print(counter("retries")); // {retries: 0, retriesMax: 10}

let fields = ["host", "port"].map(f => ({ [f]: nil }));
print(fields);              // [{host: nil}, {port: nil}]
print({ [1]: "one" }); // TypeError: Object properties must be accessed with string keys.
  • has(k) — whether the object has the key k.
  • get(k[, default]) — the value of k, or default (nil if not given) when missing; obj[k] and obj.k are a KeyError instead.
  • keys(), values(), entries() — new arrays of the keys, the values, or [key, value] pairs, in the order the keys were added, as for walks them.
  • delete(k) — removes k in place and returns whether it was there.
let mut config = { port: 8080, host: "localhost", debug: false };

print(config.has("port"));             // true
print(config.get("user"));             // nil
print(config.get("user", "admin"));    // admin
print(config.keys());                  // ["port", "host", "debug"]
print(config.values());                // [8080, "localhost", false]
print(config.entries());               // [["port", 8080], ["host", "localhost"], ["debug", false]]
print(config.delete("debug"));         // true
print(config.delete("debug"));         // false
print(config);                         // {port: 8080, host: "localhost"}

entries() pairs well with array destructuring:

let prices = { apple: 1.2, pear: 0.8 };
for [fruit, price] in prices.entries() {
    print("{fruit}: {price}");
}
// apple: 1.2
// pear: 0.8

Reading o.k gives an own property of that name first; a call o.k() always calls the method:

let stats = { keys: 3 };
print(stats.keys);          // 3
print(stats.keys());        // ["keys"]