简体   繁体   中英

For loop inside my custom function doesn't work

I'm trying to create a function that uses the number input I got from users to create the same amount of division inside of a container division.However, no matter what the number is, it always creates only 1 div. It seems like the for loop inside my function is being avoided.

I've tried to alter the function, checked number input whether it is defined or undefined.

function createGrid(parameter) {
  for (i = 0; i < parameter * parameter; i++); {
    const div = document.createElement('div');
    newDiv = container.appendChild(div);
    newDiv.setAttribute('class', 'newDiv');
  }
  return newDiv;
}

You have semicolon ; after for loop which is essentially an empty statement.

That is the reason the for loop is not working as expected, and rest of your code is just creating one divider.

Remove the semicolon ; to fix the issue.

Additional to Nikhil's answer, here is how I would write it (without using global variables, which is considered to be bad practice in most cases):

function createGrid(parameter) {
  let newDiv;
  for (let i = 0; i < parameter * parameter; i++) {
    newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
  return newDiv;
}

If you don't need to return the last div added, just remove the let newDiv; line and put the const keyword back into the first line of the for loop. Also remove the return value then.

function createGrid(parameter) {
  for (let i = 0; i < parameter * parameter; i++) {
    const newDiv = document.createElement('div');
    newDiv.setAttribute('class', 'newDiv');
    container.appendChild(newDiv);
  }
}

It is because you have to declare the variable "i", try this:

function createGrid(parameter){
  for(let i = 0 ; i < parameter*parameter; i++);{
    const div = document.createElement('div');
    newDiv = container.appendChild(div);
    newDiv.setAttribute('class','newDiv');}
  return newDiv;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM