Forem

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! 😊

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay