![]() |
Generating a range of numbers and characters means creating a sequential series of numerical values or characters, typically within specified start and end points, forming a continuous sequence or collection. Approaches to Generate a Range of Numbers and Characters Using JavaScriptTable of Content Using Array from() and charCodeAt() methodIn this approach, Array.from() is a JavaScript method that creates an array from an iterable or array-like object. It’s often used to generate arrays of numbers, characters, or other elements based on specified conditions, making it versatile for data manipulation. charCodeAt() returns the Unicode of the character whose index is provided to the method as the argument. Syntax:Array.from(object, mapFunction, thisValue) Example: In this example we will generate the numbers and characters in the given range using array from and charCodeAt method.
Output [ 1, 2, 3, 4, 5, 6, 7, 8 ] [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ] Using For…in loop methodUsing a for…in loop, we iterate through the indices of an array-like object, performing a specific action for each index. It’s often used to traverse object properties but can be adapted for other tasks like generating sequences. Syntax:for (let i in obj1) { Example: In this example, we will use For..in loop to generate numbers in the given range.
Output [ 1, 2, 3, 4, 5, 6, 7, 8 ] Using for loop methodIn this apporach, we are using for loop to iterate through character codes between ‘A’ and ‘G’, converting each code to its corresponding character and appending it to the result array, Syntax:for (statement 1 ; statement 2 ; statement 3){ Example: In this example, we will use JavaScript For loop to generate the characters in the given range.
Output [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ] Using while LoopThe while loop is another method for iterating over a sequence of values, executing a block of code as long as a specified condition is true. This approach can be particularly useful for generating sequences when the end condition is not known beforehand. Example: In this example, we will use a while loop to generate both numbers and characters in the specified range.
Output [ 1, 2, 3, 4, 5, 6, 7, 8 ] [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |