Home > Software design >  JavaScript for loop that alternates two constants
JavaScript for loop that alternates two constants

Time:02-17

I've been trying to use a for loop to make a code that alternates between two strings and ends with .toUpperCase , but I'm completely stuck. I'm "able" to do it with an array with two strings (and even so it has a mistake, as it ends with the first string of the array...), but not with two separate constants.
Could anyone offer some help?

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  let result = "";
  for (let i = 0; i < num; i  ) {
    result  = i === num - 1 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
  }
  return result;
}
console.log(repeteFrases(2));

CodePudding user response:

In order to alternate between two states you can use the parity of the index, i.e., the condition would be i % 2 == 0, like this:

   function repeteFrases(num) {
     const frases = ["frase um", "frase dois"];
     let result = "";
     for (let i = 0; i < num; i  ) {
       result  = i % 2 == 0 ? frases[0].toUpperCase() : `${frases[0]}, ${frases[1]}, `;
     }
     return result;
   }
   console.log(repeteFrases(5));

CodePudding user response:

You've almost got it.. I think what you're asking for is to repeat phrase one or two (alternating), and for the last version to be uppercase. I notice someone else made your code executable, so I might be misunderstanding. We can test odd/even using the modulus operator (%), which keeps the access of frases to either the 0 or 1 position. The other trick is to loop until one less phrase than needed, and append the last one as upper case.

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  //Only loop to 1 less than the expected number of phrases
  const n=num-1;

  let result = "";
  for (let i = 0; i < n; i  ) {
    //Note %2 means the result can only be 0 or 1
    //Note ', ' is a guess at inter-phrase padding
    result =frases[i%2]   ', ';
  }
  //Append last as upper case
  return result frases[n%2].toUpperCase();
}
console.log(repeteFrases(2));
console.log(repeteFrases(3));

CodePudding user response:

Use frases[i % frases.length] to alternate the phrases (however many there might be)

function repeteFrases(num) {
  const frases = ["frase um", "frase dois"];
  let result = "";
  for (let i = 0; i < num; i  ) {
    const next = frases[i % frases.length];
    const isLast = (i === num - 1);
    result  = isLast ? next.toUpperCase() : `${next}, `;
  }
  return result;
}

console.log(repeteFrases(5));

  • Related