0

I want to optimize my javascript code with a FOR by i can't do this and i don't know why.

My code :

let pokemon1 = 'premier';
let pokemon2 = 'second';
let pokemon3 = 'troisieme';
for (var i = 1; i < 4; i++) {
     console.log(pokemon[i]);
}

Do you know why it doesn't work ? Thank you very much and sorry if i am a noob.

  • 4
    The `[ ]` is for **arrays**. Declare `pokemon` as an array and your code will work. – Pointy Oct 24 '17 at 23:41
  • 1
    `console.log(eval('pokemon'+i))` hehehehe *evil grin* – vol7ron Oct 24 '17 at 23:42
  • Variable variables are almost always the wrong approach. Learn about data structures instead: http://eloquentjavascript.net/04_data.html . – Felix Kling Oct 24 '17 at 23:45
  • @FelixKling This is clearly not a duplicate, OP as a beginner in code doesn't know about arrays and was clearly wondering if something existed to handle that kind of data. – Loïc Oct 25 '17 at 03:00

2 Answers2

1

Since you are using a list, you should use [] to define an array :

let pokemons = ['premier', 'second', 'troisième'];
for (let i = 0; i < pokemons.length; i++) {
     console.log(pokemons[i]);
}

See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array for more information.

Also you should note that the first element of a list is 0.

So basically pokemons[0] === 'premier and pokemons[2] === 'troisième'

Loïc
  • 11,804
  • 1
  • 31
  • 49
1

You should place the pokemon in an array:

let pokemon = [];
pokemon[0] = "premier";
pokemon[1] = "second";
pokemon[2] = "troisieme";
for(var i = 0; i < pokemon.length; i++){
 console.log(pokemon[i])
};

Followed by some reading time: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

jcarapia
  • 578
  • 1
  • 7
  • 20