Arrays
Arrays are the first type of collections in Sonar.
An array is a collection of values that are indexed by their ordinal position. This means that arrays store collections of data, and each value can be retrieved if you know its position in the array.
Each value stored in an array is called an element of the array. An element can be a number, a string, a boolean, a map or even another array.
Arrays are created using the array operator, which is just two square brackets written together.
Arrays can be created with values in them.
After an array has been created, you can add elements to it using the push
function. The push
function requires at least two arguments: the array to push the element to, and the new element(2). push always returns a new array (one containing the old and new elements), so you must rememeber to save this new array to your old variable.
Unlike several languages, Sonar arrays are heterogenous –– they can store elements of different types.
Popping Elements from Arrays
The push() function pushes new elements onto arrays. To reverse the process, we can use pop().
pop() removes (or pops) the last element from the array and returns the removed element (push() returns the new array).
Accessing Specific Elements in an Array
Each element in an array has a unique label that is related to its position in the array. The first element is at position 1, the second at position 2, and so on. Arrays work much like a queue at the bank or the airport.
The label associated with an element is called its index, and it is always equal to the position of the element minus 1. The first element has a position of 1, and an index of 0; the second element has a position of 2, and an index of 1; and so on. The reason for this is that computers (and computer programs) have always counted the elements of their arrays from 0, and its worked great so far. Although there are thousands of programming languages, this is one point that everybody actually agrees on.
To access an element in an array, you'll need to use the accessor operator ([]), with the index of the element written between the square brackets.
But using an impossible index (such as one that is equal to, or greater than, the number of elements in the array) doesn't work. It returns an error.
Sonar allows you to use negative numbers to index your arrays. When the index in your accessor is a negative number, Sonar starts indexing from the end of the array.
You can change the value of the element at a specific index using accessor assignment.
Last updated