Home > Net >  Create a method that creates a new array based on the values ​passed
Create a method that creates a new array based on the values ​passed

Time:10-22

What is the best way to implement a method that creates a new array based on the values ​​passed. Method entries (3, a), Method result: ['a', 'a', 'a']

It's a question of an exercise, but I wasn't able to interpret the question.

I was trying this:

const arr = [];
arr.push(3, 'a');

console.log(arr);

CodePudding user response:

Very simple Funktion. Just a FOR loop and then array push() function.

function makeArray(num, val) {
    const newArray= [];
  for (let i = 0; i < num; i  ) {
    newArray.push(val);
  }
  return newArray;
}

const result = makeArray(3,'a');
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related