How to get a array lengh?

is there a method or attribute like js (arr.length) ?

2 Likes

Try this:

arr.size()
5 Likes

It’s strange such a fundamental API is not documented, (or hard to find in the document)

4 Likes

You are totally right.

I was surprised to find that it was not here: Array :: Internet Computer

Short term: i’ll make sure its added.

Medium term: we are in the middle of an entire overhaul of the documentation (because none of us are happy with it)

2 Likes

Because .size() is actually not defined in the base library, but comes directly from the compiler. Having said that, I fully agree that in the name of discoverability we should at least mention it in that module (just like the generated == operator, when the compiler is able to generate it).

Edit: I had to dive a bit into the docs and find it buried deep in the language overview chapter of the Motoko guide: Smart Contracts on the Internet Computer

So it is there, but we could do better. The search engine for the site also didn’t come up with this.

2 Likes

Thank you, Gabor. This is helpful

I think a simple short-term fix would be to add a wrapper to the Array module. Something like:

public func size<A>(xs : [A]) : Nat = xs.size();

Same goes for other things where this comes up.

2 Likes

This is not in the docs yet right? Internet Computer Content Validation Bootstrap

@diegop

Can you track how devs interact with the docs? I’d be so curious to see what they run into.

I made a PR:

3 Likes

Array.size() is released now: Release 0.7.6 · dfinity/motoko · GitHub
Please note that dfx may need a few days to catch up.

Edit: dfx-0.13.0-beta.1 has caught up!

4 Likes