Display value of an Indice array in an Alert

Asked

Viewed 547 times

-4

Hello

How do I display a value of an array Indice in an Alert in javascript?

a[i] = "Carro";
alert(a[i]);

Thank you

3 answers

0


Apparently your idea of how to display the value is not wrong, just fix the syntax.

var a = [];
a[0] = 'Carro';
alert(a[0]); 

In case the array is inside a loop:

    var a = [];
    a[0] = 'Carro';
    
    for (i = 0; i < 1; i++) {
      alert(a[i]);
    }   
   

0

What you’re trying to do is use the variable i to declare the Indian, however, is not within a for

let arr = ["Carro", "Avião", "Moto"]

// Aqui você faz passando o indice manualmente
alert(arr[0])

// Nesse caso você usa o I, ele irá percorrer todos os indices
for(let i = 0; i < arr.length; i++){
  console.log(arr[i])
}

0

Question not very clear.

First of all, there’s no need to go around

var a = [];
a[0] = 'Carro';
alert(a[0]);

to display this alert simply alert("Carro");

The way the question is asked (and kept inside a loop) would have that return:

var a = ["Saab", "Volvo", "BMW"];

    for (i = 0; i < a.length; i++) {
      //a cada iteração o valor do elemento é alterado para Carro
      a[i] = "Carro";
      console.log(a[i]);
    }

Most likely you are wanting the below

Inside a loop to display array elements

var a = ["Saab", "Volvo", "BMW"];

    for (i = 0; i < a.length; i++) {
      console.log(a[i]);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.