Home > Web Front-end > JS Tutorial > How Can I Create a Range Function in JavaScript Similar to PHP's range()?

How Can I Create a Range Function in JavaScript Similar to PHP's range()?

Susan Sarandon
Release: 2024-12-14 21:24:13
Original
324 people have browsed it

How Can I Create a Range Function in JavaScript Similar to PHP's range()?

Does JavaScript Have a Range Function Like PHP's range()?

PHP's range() function allows you to effortlessly generate an array of numbers or characters within specified bounds. However, JavaScript does not have a built-in function for this purpose. Here are a few methods to implement this functionality in JavaScript:

Numbers

Utilize the Array.keys() method:

[...Array(5).keys()]; // [0, 1, 2, 3, 4]
Copy after login

Character Iteration

Leverage String.fromCharCode() to iterate through character ranges:

String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
// "ABCD"
Copy after login

Generic Iteration

Employ for...of loops in conjunction with String.fromCharCode():

for (const x of Array(5).keys()) {
  console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
// 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"
Copy after login

Custom Range Functions

Create reusable functions to generate ranges:

function range(size, startAt = 0) {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar, endChar) {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
Copy after login

As Typed Functions

TypeScript users can define typed functions:

function range(size:number, startAt:number = 0):ReadonlyArray<number> {
    return [...Array(size).keys()].map(i => i + startAt);
}

function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
    return String.fromCharCode(...range(endChar.charCodeAt(0) -
            startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
Copy after login

External Libraries

Alternatively, you can utilize third-party libraries such as lodash.js, which provides a range() function:

_.range(10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy after login

The above is the detailed content of How Can I Create a Range Function in JavaScript Similar to PHP's range()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template