Home > Back-end >  Why my for loop give me always the same result?
Why my for loop give me always the same result?

Time:11-10

I try to make an exercise where you have to calculate multiplication here is the code to create the questions.

   const [questionsArray,setQuestionsArray] = useState([]);
   const [multiplyArray, setMultiplyArray] = useState([35]);
   const [multBy, setMultBy] = useState(5);

   function createQuestionsArray() {
     for (var m = 0; m < multiplyArray.length; m  ) {
       for (var b = 1; b < multBy 1; b  ) {
         var question = multiplyArray[m] 'x' b;
         setQuestionsArray((prev) => [...prev, question]);
       }
     }
   }

So what I want at the end is questionArray = [35x1,35x2,35x3,35x4,35x5] but I have questionArray = [35x5,35x5,35x5,35x5,35x5]. What is the problem? please

CodePudding user response:

Well, I did same thing but with "while" and it worked, so I still don't understand the problem but I can continue my app ^^

Should I delete my question?

CodePudding user response:

Hmm, where is prev coming from in setQuestionsArray(...)?

Why not use:

        setQuestionsArray( [...questionsArray, question] );

Edit: Weird that the while loop fixed it... Converting this to vanilla javascript works:

const multiplyArray = [35];
const multBy = 5;
let questionsArray = [];

function createQuestionsArray() {
 for (var m = 0; m < multiplyArray.length; m  ) {
   for (var b = 1; b < multBy 1; b  ) {
     var question = multiplyArray[m] 'x' b;
     questionsArray = [...questionsArray, question];
   }
 }
}

createQuestionsArray();

// questionsArray = [ '35x1', '35x2', '35x3', '35x4', '35x5' ]
  • Related