Introduction
In this lab, we will explore the implementation of a function called initializeArrayWithRange in JavaScript. This function initializes an array containing the numbers in a specified range, with the option to include a step value. We will learn how to use Array.from(), the map() function, and default parameter values to create a flexible and reusable function for generating arrays with a range of values.
Function to Initialize Array with Range
To initialize an array with a range of numbers, use the following function:
const initializeArrayWithRange = (end, start = 0, step = 1) => {
const length = Math.ceil((end - start + 1) / step);
return Array.from({ length }, (_, i) => i * step + start);
};
This function takes three arguments: end (required), start (optional, default value is 0), and step (optional, default value is 1). It returns an array containing the numbers in the specified range, where start and end are inclusive with their common difference step.
To use this function, simply call it with the desired range parameters:
initializeArrayWithRange(5); // [0, 1, 2, 3, 4, 5]
initializeArrayWithRange(7, 3); // [3, 4, 5, 6, 7]
initializeArrayWithRange(9, 0, 2); // [0, 2, 4, 6, 8]
This function uses Array.from() to create an array of the desired length, and then a map function to fill the array with the desired values in the given range. If you omit the second argument, start, it will use a default value of 0. If you omit the last argument, step, it will use a default value of 1.
Summary
Congratulations! You have completed the Initialize Array With Range lab. You can practice more labs in LabEx to improve your skills.