JavaScript Implements the Number M to Form an Array of N Elements

Need

To implement an array of n numbers, you can use JavaScript to write a function that generates such an array.

Option One

Here is an example function that takes two arguments n and m and produces an array of n elements, where each element is m:

function generateArray(n, m) {
   if (n <= 0) {
     return [];
   }

   const array = [];
   for (let i = 0; i < n; i++) {
     array.push(m);
   }

   return array;
}

// Usage example
const n = 5; //The number of elements in the array
const m = 10; // element value in array
const resultArray = generateArray(n, m);
console. log(resultArray);

In the example above, the generateArray function accepts two parameters: n (the number of elements in the array) and m (the value of the element to be placed in the array). It first checks if n is less than or equal to 0, and if so, returns an empty array. Otherwise, it creates an empty array and uses a loop to add n m to the array, finally returning the resulting array.

You can generate an array of n elements, each of which is m, by calling generateArray(n, m) and passing in the appropriate arguments. In the example above, we generate an array with 5 elements, each element being 10, and print the result to the console.

Option Two

You can use JavaScript's Array.fill() method to generate an array containing n elements, each element being m. This is a cleaner approach that doesn't require using a loop. Here is an example using the fill() method:

function generateArray(n, m) {
   if (n <= 0) {
     return [];
   }

   return new Array(n).fill(m);
}

// Usage example
const n = 5; // the number of elements in the array
const m = 10; // element value in the array
const resultArray = generateArray(n, m);
console. log(resultArray);

Comments