DEV Community

Cover image for Matrizes ou Arrays Multidimensionais
ananopaisdojavascript
ananopaisdojavascript

Posted on

2 1

Matrizes ou Arrays Multidimensionais

⚠️ ALERTA!!!! ⚠️

Matrizes não são algo que vemos com frequência no JS. Coloquei aqui mais por conhecimento mesmo e porque elas existem.

As matrizes são vetores de duas ou mais dimensões (arrays multidimensionais) que também guardam elementos do mesmo tipo. Essa funcionalidade não existe no JS, porém podemos criá-la da seguinte forma: fazendo um array principal e, dentro, colocar outros arrays.

Exemplo

const numeros = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
];

console.log(numeros.join("\n\n"));
Enter fullscreen mode Exit fullscreen mode

O resultado aparece assim:

/*

"1,2,3,4,5

6,7,8,9,10"

*/
Enter fullscreen mode Exit fullscreen mode

E como eu faço para mostrar um determinado elemento dessa matriz?!

É só fazer assim:

const numeros = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
];

console.log(numeros[0][0]); // 1
console.log(numeros[1][0]); // 2
Enter fullscreen mode Exit fullscreen mode

É melhor explicar:

A matriz numeros consiste em dois vetores com cinco elementos cada. O primeiro índice entre colchetes refere-se ao índice do vetor (linha), enquanto que o segundo índice refere-se ao elemento que está dentro desse vetor (coluna).

Como faço para percorrer e mostrar todos os elementos da matriz?

Vamos usar o laço for of.

for (let [d1, d2, d3] of numeros) {
  console.log(`${d1}, ${d2}, ${d3}`)
}
Enter fullscreen mode Exit fullscreen mode

Ou podemos usar for in.

for (let i of numeros) {
  for (let j of i) {
    console.log(j)
  }
}
Enter fullscreen mode Exit fullscreen mode

E aí? Gostaram? Até a próxima anotação! 😊

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more