Nicholas Ritson
Nicholas Ritson

Reputation: 909

es6 for loop not looping

I am trying to get a simple ES6 for-loop working but cant figure out why its not running.

I've copied an example from developer.mozilla docs and I've also tried it with the eslinter version which is below:
I have also added a let i = 0; above. All it renders/logs is i = 0 and wont increment. the eslint version is here: eslint site

  for (i = 0; i < 10; i += 1) {
    console.log('i', i);
    return <p>component {i}</p>;
  }

Edit: ok got the values coming back in the log as i=0, i=1, etc... but to get them into a component each? i tried the push into array and mapping through to get the components out but i get no error and nothing appearing, even if i try just getting a value out.

const nbPageArray = [];
  let i = 0;
  for (i = 0; i < nbPages; i += 1) {
    console.log('i', i);
    nbPageArray.push(<p>component {i}</p>);
  }
  console.log('array', nbPageArray);
  nbPageArray.map(a => <p>{a.type}</p>);
}

final working version:

const nbPageArray = [];
for (let i = 0; i < nbPages; i += 1) {
  nbPageArray.push({ page: i + 1 });
}
return nbPageArray.map(a =>
  <li className="page-item"><a className="page-link">{a.page}</a></li>,
);

Upvotes: 0

Views: 150

Answers (4)

Vivek Doshi
Vivek Doshi

Reputation: 58593

Main issue is i += 10;

That should be 1 += 1;

And You should return array of elements :

var p_tags = [];
for (i = 0; i < 10;  i += 1) {
    console.log('i', i);
    p_tags.push(<p>component {i}</p>);
}
return p_tags;

Edited question's answer :

First Error:

const nbPageArray = []; should be var nbPageArray = [];

Second You are not returning the array so change your code to this

return nbPageArray.map(a => <p>{a.type}</p>);

Upvotes: 1

Fez Vrasta
Fez Vrasta

Reputation: 14835

As said in the comments, the return inside the for loop is going to exit from the function at the first iteration.

You can do something like this instead:

const result = Array(10).fill().map((_, i) =>
  <p>component {i}</p>
);

Or

const result = [...Array(10)].map((_, i) =>
  <p>component {i}</p>
);

Upvotes: 0

Sri
Sri

Reputation: 1336

you are returning from the loop and also incrementing by 10. The loop will execute only once.

Upvotes: 0

OArnarsson
OArnarsson

Reputation: 960

If you return from your for loop, you will exit the current function, you are also incrementing i by 10 each trip so you will exit the loop after one round either way.

If you are trying to print a string with the value of i ten times you could try using template string like so:

for (i = 0; i < 10; i += 1) {
  console.log('i', i);
  console.log(`<p>component ${i}</p>`);
}

Upvotes: 0

Related Questions