Ad

How To Use The Do While Loop To Push A String Into An Array Multiple Times?

I am very close...I think. Trying to use a do while loop to push "I love the Beatles!" into the array (n) amount of times including the 0 of whatever number is entered.

Implement a do-while loop inside the function that adds "I love the Beatles!" to the empty array.

The loop should then increment the number passed in as a parameter. The condition of the loop should check to see that the parameter number is less than 15. It should contain a number of strings that represents the difference between the input number and 15.

Return the array with the strings "I love the Beatles!".

I have tried what I have learnt so far on this course. Any explanation would be much appreciated!

function iLoveTheBeatles(n) {
  let newArray = [];
  let LoveBeatles = newArray.push("I love the Beatles!");

  do {
    LoveBeatles;
    return newArray;
  } while (n < 15);

  if (n > 15)
    newArray.push(LoveBeatles);

  return newArray;
}
1) Beatles Loops iLoveTheBeatles returns an 
array of 'I love the Beatles!' 8 times 
when passed the parameter 7 :

Error: Expected [ 'I love the Beatles!' ] 
to equal 
[ 'I love the Beatles!', 'I love the Beatles!', 
'I love the Beatles!', 'I love the Beatles!', 
'I love the Beatles!', 'I love the Beatles!', 
'I love the Beatles!', 'I love the Beatles!' ]

Ad

Answer

Just make LoveBeatles a function. You also need to return from the function at the end - and increment n to avoid an infinite loop.

function iLoveTheBeatles(n) {
  let newArray = [];
  let LoveBeatles = () => newArray.push("I love the Beatles!");
  do {
    LoveBeatles();
    n++;
  } while (n < 15);
  if (n > 15) LoveBeatles();
  return newArray;
}

const res = iLoveTheBeatles(7);

console.log(res);
console.log(res.length);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Ad
source: stackoverflow.com
Ad