Home > Back-end >  for loop calculation syntax within a function is not correct
for loop calculation syntax within a function is not correct

Time:11-02

what is the actual syntax for the for loop? what I want to do is to calculate 2 number variables inside a function using a for a loop. I am going over and over the internet and I cannot find anything that can help me specifically for this task I was given to do. I am not looking for the answers, just for a guideline or a hint. or just give me the syntax and I will try my best to adjust it to my needs. just so you have a better understanding of the task, here it is.

Features
Instead of hardcoding Y (the result of the Fibonacci of X), calculate it with a for loop
The calculation should be wrapped in a function, that gets X as an argument, and returns Y
After the function, you should call the function, and assign the returned value in your HTML to present to the user

btw, i know that i did not put the innerHTML correcly, and also i did not do the syntax right, this is actually what i am asking here.

thank you!!

i have tried this:

var answer = document.getElementsByClassName("paragraph")
function calc (x){
    for (let a = 2; a <= x; a  ){
        answer = document.textContent("this is a pr")
    }
    return calc
}
calc(2)

CodePudding user response:

You should avoid to use classname, instead use .querySelectorAll
You don't need to specify how many answer exists if your calc() is just 2.

let answer = document.querySelectorAll(".paragraph");
    
function calc(x) {
  for (let a = 0; a <= x; a  ) {
    answer[a].innerText = "this is a pr";
  }
}

calc(2);
<p >A</p>
<p >B</p>
<p >C</p>
<p >D</p>
<p >E</p>

I don't know if this is what you're searching for but it's this is the standard for loop function to achieve these types of result.

CodePudding user response:

The Syntax of the loop in your code is correct, the thing is that you cannot return your function inside itself without calling it as you have done in your code.

'return calc' is wrong. You should use 'return calc(argument-Variable or value)' as you have a parameter passed in your function, but this should only be used if you are writing a code of recursion. If not you should return a variable.

  • Related