Lists (JavaScript)

Lists

> Tutorial

A list lets you store several values in a specific order.

Creating and using a list

You can create a list with the following syntax:

The first position in a list is position 0. You access a specific element of the list like this:

Many operations are available for working with lists. The most notable ones are:

Iterating over a list with the for of loop

You can iterate over each value in a list using a simple for loop, like this:

But there is a variant of the for loop that makes iterating over each value of a list simpler: the for of loop. The following code is equivalent to the previous one, but more concise:

Estimating weapon damage and the "finisher" condition

Our current AI has a problem: when the enemy is almost dead, our leek uses its boosts, heals and shields before using its weapon, when it could have finished the enemy off!

To handle this end-of-fight situation better, we'll estimate the damage we can deal to the enemy, to know whether we can finish it off.

We start by getting the list of our weapon's features with me.weapon.features:

Each feature has properties: .type (the effect type), .minValue (minimum value), .maxValue (maximum value)... When the feature is damage, we calculate the final damage:

We add the damage to the total:

We finish with a condition: if the total damage is greater than the enemy's life, we'll kill it, so we attack! Otherwise, we wait and use chips:

> Tip: you can extract a range from a list with list.slice(2, 8).

> Tip: lists can be nested, with a list inside a list [ [1, 2, 3] ], and you access a list inside a list with list[0][0].

❓ Quiz

What can a list be used for?

Storing several values Sorting values Running instructions in parallel Performing several calculations

Which pieces of code are valid?

let a = [1, 2, 3] a[0] + a[2] let [1, 2, 3] [1, 2, 3].length [ [1, 2], [3, 4], [5, 6] ] list[5][10]

Full AI