Array JavaScript (com exemplos)

Neste tutorial, você aprenderá sobre array JavaScript com a ajuda de exemplos.

Como você sabe, uma variável pode armazenar um único elemento. Se você precisa armazenar vários elementos de uma vez, pode usar um array.

Uma matriz é um objeto que pode armazenar vários elementos . Por exemplo,

 const myArray = ('hello', 'world', 'welcome');

Crie um Array

Você pode criar uma matriz de duas maneiras:

1. Usando um array literal

A maneira mais fácil de criar uma matriz é usando um literal de matriz (). Por exemplo,

 const array1 = ("eat", "sleep");

2. Usando a nova palavra-chave

Você também pode criar uma matriz usando a newpalavra-chave do JavaScript .

 const array2 = new Array("eat", "sleep");

Em ambos os exemplos acima, criamos uma matriz com dois elementos.

Observação : é recomendável usar o literal de array para criar um array.

Aqui estão mais exemplos de matrizes:

 // empty array const myList = ( ); // array containing number values const numberArray = ( 2, 4, 6, 8); // array containing string values const stringArray = ( 'eat', 'work', 'sleep'); // multiple data types array const newData = ('work', 'exercise', 1, true);

Você também pode armazenar matrizes, funções e outros objetos dentro de uma matriz. Por exemplo,

 const newData = ( ('task1': 'exercise'), (1, 2 ,3), function hello() ( console.log('hello')) );

Elementos de acesso de uma matriz

Você pode acessar os elementos dentro de uma matriz usando índices (0, 1, 2 …) . Por exemplo,

 const myArray = ('h', 'e', 'l', 'l', 'o'); // first element console.log(myArray(0)); // "h" // second element console.log(myArray(1)); // "e"
Indexação de matriz em JavaScript

Nota : o índice da matriz começa com 0, não 1.

Adicionar um elemento a um array

Você pode usar o método integrado push()e unshift()adicionar um elemento a uma matriz.

O push()método adiciona um elemento no final de uma matriz e retorna o comprimento de uma nova matriz. Por exemplo,

 let dailyActivities = ('eat', 'sleep'); // add an element at the end of the array dailyActivities.push('exercise'); console.log(dailyActivities); // ('eat', 'sleep', 'exercise')

O unshift()método adiciona um novo elemento ao início de uma matriz e retorna o novo comprimento de uma matriz. Por exemplo,

 let dailyActivities = ('eat', 'sleep'); //add an element at the end of the array dailyActivities.unshift('work'); console.log(dailyActivities); // ('work', 'eat', 'sleep', 'exercise'')

Mudar os elementos de um array

Você também pode adicionar elementos ou alterar os elementos acessando o valor do índice.

 let dailyActivities = ( 'eat', 'sleep'); // this will add the new element 'exercise' at the 2 index dailyActivities(2) = 'exercise'; console.log(dailyActivities); // ('eat', 'sleep', 'exercise')

Suponha que uma matriz tenha dois elementos. Se você tentar adicionar um elemento no índice 3 (quarto elemento), o terceiro elemento será indefinido. Por exemplo,

 let dailyActivities = ( 'eat', 'sleep'); // this will add the new element 'exercise' at the 3 index dailyActivities(3) = 'exercise'; console.log(dailyActivities); // ("eat", "sleep", undefined, "exercise")

Basicamente, se você tentar adicionar elementos a índices altos, os índices intermediários terão valor indefinido.

Remover um elemento de uma matriz

Você pode usar o pop()método para remover o último elemento de uma matriz. O pop()método também retorna o valor retornado. Por exemplo,

 let dailyActivities = ('work', 'eat', 'sleep', 'exercise'); // remove the last element dailyActivities.pop(); console.log(dailyActivities); // ('work', 'eat', 'sleep') // remove the last element from ('work', 'eat', 'sleep') const removedElement = dailyActivities.pop(); //get removed element console.log(removedElement); // 'sleep' console.log(dailyActivities); // ('work', 'eat')

Se você precisar remover o primeiro elemento, pode usar o shift()método. O shift()método remove o primeiro elemento e também retorna o elemento removido. Por exemplo,

 let dailyActivities = ('work', 'eat', 'sleep'); // remove the first element dailyActivities.shift(); console.log(dailyActivities); // ('eat', 'sleep')

Comprimento da matriz

You can find the length of an element (the number of elements in an array) using the length property. For example,

 const dailyActivities = ( 'eat', 'sleep'); // this gives the total number of elements in an array console.log(dailyActivities.length); // 2

Array Methods

In JavaScript, there are various array methods available that makes it easier to perform useful calculations.

Some of the commonly used JavaScript array methods are:

Method Description
concat() joins two or more arrays and returns a result
indexOf() searches an element of an array and returns its position
find() returns the first value of an array element that passes a test
findIndex() returns the first index of an array element that passes a test
forEach() calls a function for each element
includes() checks if an array contains a specified element
push() aads a new element to the end of an array and returns the new length of an array
unshift() adds a new element to the beginning of an array and returns the new length of an array
pop() removes the last element of an array and returns the removed element
shift() removes the first element of an array and returns the removed element
sort() sorts the elements alphabetically in strings and in ascending order
slice() selects the part of an array and returns the new array
splice() removes or replaces existing elements and/or adds new elements

Example: JavaScript Array Methods

 let dailyActivities = ('sleep', 'work', 'exercise') let newRoutine = ('eat'); // sorting elements in the alphabetical order dailyActivities.sort(); console.log(dailyActivities); // ('exercise', 'sleep', 'work') //finding the index position of string const position = dailyActivities.indexOf('work'); console.log(position); // 2 // slicing the array elements const newDailyActivities = dailyActivities.slice(1); console.log(newDailyActivities); // ( 'sleep', 'work') // concatenating two arrays const routine = dailyActivities.concat(newRoutine); console.log(routine); // ("exercise", "sleep", "work", "eat")

Note: If the element is not in an array, indexOf() gives -1.

Visit JavaScript Array Methods to learn more.

Working of JavaScript Arrays

In JavaScript, an array is an object. And, the indices of arrays are objects keys.

Como as matrizes são objetos, os elementos da matriz são armazenados por referência. Portanto, quando um valor de matriz é copiado, qualquer alteração na matriz copiada também se refletirá na matriz original. Por exemplo,

 let arr = ('h', 'e'); let arr1 = arr; arr1.push('l'); console.log(arr); // ("h", "e", "l") console.log(arr1); // ("h", "e", "l")

Você também pode armazenar valores passando uma chave nomeada em uma matriz. Por exemplo,

 let arr = ('h', 'e'); arr.name = 'John'; console.log(arr); // ("h", "e") console.log(arr.name); // "John" console.log(arr('name')); // "John"
Indexação de matriz em JavaScript

No entanto, não é recomendado armazenar valores passando nomes arbitrários em uma matriz.

Portanto, em JavaScript, você deve usar uma matriz se os valores estiverem em uma coleção ordenada. Caso contrário, é melhor usar o objeto com ( ).

Artigos Recomendados

  • JavaScript para cada
  • JavaScript para … de
  • Array multidimensional de JavaScript

Artigos interessantes...