How to add a string to an array and return the string

Tags: , , ,



Build a function forLoop. It takes an array as an argument. Start counting from 0, and, using a for loop, add a string to the array 25 times. But not just any string. If your i value is 1, add the string “I am 1 strange loop.”; if your i value is anything else, add the string “I am ${i} strange loops.”. (Remember flow control with if and else? And how do we interpolate i?) Then return the array.

Learning online and am having trouble understanding what is needed to return the array with the string added to it 25 times?

function forLoop(array) {
  for (let i = 0; i < 25; i++) {
    if (i === 1) {
      console.log(`${array} I am 1 strange loop.`);
    } else {
      console.log(`${array}I am ${i} strange loops.`);
    }
  }
}

forLoop(array);

adds `"I am ${i} strange loop${i === 0 ? '' : 's'}."` to an array 25 times:
TypeError: Cannot read property 'slice' of undefined    

Answer

You’re close. You simply need to push the string to the array, and then return the array at the end.

function forLoop(arr) {
  for (let i = 0; i < 25; i++) {
    if (i === 1) {

      // Use `push` to add the string to the array
      arr.push(`I am 1 strange loop.`);
    } else {
      arr.push(`I am ${i} strange loops.`);
    }
  }

  // Return your array
  return arr;
}


// Create the array and pass it into the function
const arr = [];

// `out` captures the returned array
const out = forLoop(arr);
console.log(out);


Source: stackoverflow