Home Web Front-end JS Tutorial Share advanced usage and techniques of built-in iterable objects in JS

Share advanced usage and techniques of built-in iterable objects in JS

Jan 13, 2024 am 08:42 AM
Tips sharing Advanced usage iterable object

Share advanced usage and techniques of built-in iterable objects in JS

Sharing of advanced usage and techniques of built-in JS iterable objects

Introduction:
In JavaScript, iterable objects refer to objects that can be traversed through iterators object. They are a special class of objects that provide a unified way to access their elements. There are many iterable objects built into JavaScript, such as arrays, strings, Sets, Maps, etc. This article will share some advanced usage and techniques to help you make better use of iterable objects.

1. Use for...of loop to traverse the elements of iterable objects
Using for...of loop is the most concise and intuitive way to traverse iterable objects. For example:

const arr = [1, 2, 3];
for (const elem of arr) {
  console.log(elem);
}
// 输出结果:1 2 3
Copy after login

For other iterable objects, such as strings, Sets, and Maps, you can also traverse in the same way. The for...of loop automatically calls the object's iterator to obtain elements in sequence.

2. Custom iterable objects
In addition to the built-in iterable objects, we can also customize iterable objects. Just implement the object's Symbol.iterator method and return an iterator object.

const customIterable = {
  data: [1, 2, 3, 4, 5],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.data.length) {
          return { value: this.data[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (const elem of customIterable) {
  console.log(elem);
}
// 输出结果:1 2 3 4 5
Copy after login

By customizing iterable objects, we can define the traversal method according to our own needs to meet specific business logic.

3. Convert iterable objects into arrays
Sometimes we need to convert iterable objects into arrays in order to perform array-related operations or operations.

const str = "Hello";
const arr = Array.from(str);
console.log(arr);
// 输出结果:['H', 'e', 'l', 'l', 'o']
Copy after login

Through the Array.from method, we can split the string into an array by characters. This method can be used to process iterable objects such as Strings, Sets, and Maps.

4. Use destructuring assignment to extract elements of iterable objects
We can extract elements in iterable objects through destructuring assignment.

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

for (const [key, value] of map) {
  console.log(key, value);
}
// 输出结果:key1 value1
//          key2 value2
Copy after login

Through destructuring assignment, we can extract the keys and values ​​​​in the Map at once and use them in the form of variables.

5. Use the spread operator to expand iterable objects
The spread operator (...) can be used to expand iterable objects into independent elements.

const set = new Set([1, 2, 3]);
const arr = [...set];
console.log(arr);
// 输出结果:[1, 2, 3]
Copy after login

Using the spread operator, we can expand the elements in the Set object into an array. This is useful for converting an iterable object to an array before you need to do some specific operation on it.

Conclusion:
This article shares the advanced usage and techniques of JS built-in iterable objects, including using for...of loop traversal, custom iterable objects, converting iterable objects into arrays, and using Destructuring assignment extracts elements and expands iterable objects using the spread operator. These techniques can help us make better use of iterable objects and improve the simplicity and efficiency of the code. Hope this helps!

The above is the detailed content of Share advanced usage and techniques of built-in iterable objects in JS. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Sharing tips for obtaining administrator privileges in Win11 Sharing tips for obtaining administrator privileges in Win11 Mar 08, 2024 pm 06:45 PM

Share tips on obtaining Win11 administrator rights. Microsoft's latest operating system, Windows 11, brings a new experience to users, but sometimes we need to obtain administrator rights to perform some specific operations during system operations. In the Win11 system, it is not difficult to obtain administrator rights. You only need to master some skills to complete it easily. This article will share some tips on obtaining administrator rights in Win11 to help you operate the system better. 1. Use shortcut keys to obtain administrator rights in Win11 system, use

How to check if an object is iterable in Python? How to check if an object is iterable in Python? Aug 25, 2023 pm 10:05 PM

An iterable object is an object whose all elements can be iterated over using a loop or iterable function. Lists, strings, dictionaries, tuples, etc. are all called iterable objects. In Python language, there are various ways to check whether an object is iterable. Let’s take a look one by one. Using Loops In Python, we have two looping techniques, one is using "for" loop and the other is using "while" loop. Using either of these two loops, we can check if a given object is iterable. Example In this example, we will try to iterate an object using "for" loop and check if it is iterated or not. Below is the code. l=["apple",22,"orang

Share Win11 setup tips Share Win11 setup tips Jan 03, 2024 pm 02:17 PM

The win11 system has made drastic changes to the system settings interface. It not only changed the settings interface, but also added a large number of functions. All the functions of the previous control panel were added to the settings. Let's take a look at the win11 settings tips. . Win11 setting tips 1. System settings: 1. In the system settings, you can change various setting functions such as sound, notification, power, focus mode, activation, etc. 2. You can also view our computer hardware information and system account information in the About interface. 2: Network settings 1. The new network settings can directly open the previous Network and Sharing Center. 2. You can also directly find the "Network Adapter" in the "Advanced Network Settings" of the network settings. 3. Storage settings: 1. In the storage

Git code merging skills: project experience sharing Git code merging skills: project experience sharing Nov 03, 2023 am 10:06 AM

Git code merging skills: Project experience sharing In the software development process, code merging is a very important link. Especially in multi-person collaborative development projects, branches created by different developers need to be merged to ensure the integrity and consistency of the code. This article will share some Git code merging tips and experiences to help developers merge code more efficiently. 1. Keep branches clean and synchronized. Before merging code, you must first ensure that your branches are clean and synchronized. Clean means that the branch should not contain any

Java Iterator vs. Iterable: Demystifying the World of Iterators and Iterable Objects Java Iterator vs. Iterable: Demystifying the World of Iterators and Iterable Objects Feb 19, 2024 pm 02:15 PM

In Java programming, the Iterator and Iterable interfaces are important tools for processing elements in collections. The Iterator interface provides methods for iterative access to collection elements, while the Iterable interface defines the iterability of the collection so that the elements in the collection can be accessed through Iterator. The close cooperation between the two provides us with a general method for traversing collection elements. Iterator interface The Iterator interface defines the following methods: booleanhasNext(): Check whether there are still elements in the collection. Enext(): Returns the next element in the collection. voidremove(): Remove the current element. Iterable

Lambda expression breaks out of loop Lambda expression breaks out of loop Feb 20, 2024 am 08:47 AM

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

Sharing techniques for generating video screenshots and thumbnails based on PHP Sharing techniques for generating video screenshots and thumbnails based on PHP Aug 09, 2023 pm 12:13 PM

Tips for generating video screenshots and thumbnails based on PHP. With the rapid development of the Internet, more and more websites and applications need to display video content. When displaying videos on a page, thumbnails are usually generated to provide a preview, and video screenshots may also be required to capture specific scenes. This article will introduce techniques for generating video screenshots and thumbnails based on PHP, and attach corresponding code examples. Install FFmpeg First, we need to install FFmpeg, which is a powerful multimedia processing tool that can be used for video screenshots

Tips and experience sharing on learning C language Tips and experience sharing on learning C language Feb 19, 2024 pm 09:20 PM

C Language Getting Started Guide: Learning Skills and Experience Sharing Introduction: As a classic programming language, C language has always been loved and favored by programmers. As a beginner, learning C language may face some difficulties and challenges. This article aims to share some tips and experiences in learning C language to help beginners better master this language. 1. Lay a good foundation. As a high-level programming language, mastering C language requires a good foundation. First of all, you must learn and understand the basic grammatical rules of C language, master the definition and use of variables, and the writing and calling of functions.

See all articles