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 keyk.get(k[, default])— the value ofk, ordefault(nilif not given) when missing;obj[k]andobj.kare aKeyErrorinstead.keys(),values(),entries()— new arrays of the keys, the values, or[key, value]pairs, in the order the keys were added, asforwalks them.delete(k)— removeskin 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"]