0

Below is my code

function returnEmptyTd(num) {
        for(var i=0; i <= num; i++) {
            console.log(i);
            return(
                <td class="empty"></td>
            )
        }
    }

If num is 2, I will get two empty td return. If num is 5, I will get five empty td return.

But I can only get one with this code, even I pass 5 to num.

How to fix it?

Telokis
  • 3,399
  • 14
  • 36
Dreams
  • 8,288
  • 10
  • 45
  • 71
  • Are you using React or something like that ? How do you expect the result to be ? An array ? If so, why not just pushing your `td`s inside an array and returning it ? – Telokis Mar 15 '17 at 04:10
  • @Ninetainedo Yes, I am – Dreams Mar 15 '17 at 04:11
  • https://stackoverflow.com/questions/22876978/loop-inside-react-jsx – Ry- Mar 15 '17 at 04:12
  • Don't forget that you have to use `className` in place of css' `class` when using jsx – Telokis Mar 15 '17 at 04:13
  • you're better off just mapping it (using `map`). You could do it inside the return section of render if it suits the logic. – A. L Mar 15 '17 at 05:10

2 Answers2

3

return means return and end the function.

I guess you are using React and want to render some <td> based on given num

In React you can return an array for this purpose:

var result = []
for(var i=0; i <= num; i++) {
    console.log(i);
    result.push(<td key={i} className="empty"></td>);
}
return result;
CodinCat
  • 15,530
  • 5
  • 49
  • 60
0

You Could use an array like below instead of return.

function returnEmptyTd(num) {
  var tds = [];
  for(var i=0; i <= num; i++) {
   
    tds.push('<td class="empty"></td>')
  }
  return tds;
 }
 
 var tds = returnEmptyTd(3);
 console.log(tds);
Duly Kinsky
  • 996
  • 9
  • 11