Array js giving error

Asked

Viewed 45 times

0

I got the following javaScript:

  var imagem = [];

  for (i = 0; i < quantasImagens; i++) {    

      tMin = t + tempoTransicao;
      tMax = t + tamanhoIntervalos; 
      t+=tamanhoIntervalos;

      if(i==0) tMin=0;
      if(i==quantasImagens) tMax=100;         


      imagem[i][0] = tMin + "% { margin-left:-" + tempoImagens + "%};";
      imagem[i][1] = tMax + "% { margin-left:-" + tempoImagens + "%};";

      tempoImagens+=100;

  }

  for (po=0; po<imagem.length; i++) {
      document.write(imagem[i][0]);
      document.write("<br />");
      document.write(imagem[i][1]);
      document.write("<br />");
      document.write("<br />");
  }

when the is makes the second cycle, gives error in the line:

      imagem[i][0] = tMin + "% { margin-left:-" + tempoImagens + "%};";

Saying that index 0 does not exist.

Where am I going wrong?

  • var image = []; Wrong? Note: I have tried new Array()

  • Within each imagem[i] has another array that you tb did not declare. Inside the loop.

  • But that’s what I’m asking. Teach me to declare I’ve done [[]] it didn’t work either.

1 answer

2


If each item in the image array is also an array, you need to declare them within your loop:

imagem[i] = [];
imagem[i].push(tMin + "% { margin-left:-" + tempoImagens + "%};");
imagem[i].push(tMax + "% { margin-left:-" + tempoImagens + "%};");

Notice that I’m wearing push instead of assigning directly to each index. It also works the way you did, but I prefer the push because it is the default way to insert items in arrays.

  • It actually worked. Thank you! Now I’ve learned.

Browser other questions tagged

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