Home > Web Front-end > JS Tutorial > Generate Number Ranges in JavaScript

Generate Number Ranges in JavaScript

DDD
Release: 2024-10-12 06:23:02
Original
759 people have browsed it

Generate Number Ranges in JavaScript

Generate an array of integers and fill it with consecutive values that begin with the start number and end with the end number inclusive.

Solution

function range(start, end) {
  const rangeArray = Array.from(
    {length: Math.ceil(end - start + 1)}, (_, i) => start + i);

  return rangeArray;
}

console.log(range(10, 23));
console.log(range(5, 12));
console.log(range(89, 93));
console.log(range(42, 51));
console.log(range(73, 80));
Copy after login
> [10, 11, 12, 13, 14, 15,16, 17, 18, 19, 20, 21,22, 23]
> [5,  6,  7,  8, 9, 10, 11, 12]
> [89, 90, 91, 92, 93]
> [42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
> [73, 74, 75, 76, 77, 78, 79, 80]
Copy after login

The above is the detailed content of Generate Number Ranges in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template