Array Object in JavaScript. Code example open

Array Object in JavaScript. Code example

Arrays are used to store a set of data in JavaScript. Arrays in JavaScript are represented by an Array object.

Creating an array using the Array object

    const users = new Array();//let's create an array through the Array object
    const people = [];//the usual option for creating an array

You can create an array immediately with a certain number of elements:

    const users = new Array("Alexandr", "Timote", "john", "Sergey");
    const nicknames = ["Alex3", "Timotey", "Johnson", ""];

Another way to initialize arrays is the Array.of() method – it takes elements and initializes the array with them:

    const users = Array.of("Alexandr", "Timote", "john", "Sergey");

You can define an array and define new elements into it as you go:

    const users = [];
    users[1] = "Alexander";
    users[2] = "Timote";
    console.log(users[1]); // "Alexander"

Array.from

Another way is the Array.from() function. It has many options, consider only the most common. As the first parameter, the arrayLike function takes an object, which, relatively speaking, “looks like an array“, then there can be represented as a set of elements. It can be the second array, or it can be a string.

For example:

    const array = Array.from("Hello");
    console.log(array); // ["H", "e", "l", "l", "o"]

In this case, a string is passed to the function and an array is returned, each element of which provides one of the characters of this line.

As the second parameter, a conversion function is passed, which, through the first parameter, receives the current element set and returns some result of its transformation. For example:

    const numbers = [1, 2, 3, 4];
    const array = Array.from(numbers, n => n * n);
    console.log(array); // [1, 4, 9, 16]

When the index of the converted element is also passed to the converter function:

    const array = Array.from({ length: 3 }, (element, index) => {
        console.log(element);   // undefined
        return index;
    });
    console.log(array); // [0, 1, 2]
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation