Home >Web Front-end >JS Tutorial >Learn how to use JS's built-in iterable objects effectively
In-depth understanding of how to use JS built-in iterable objects
In JavaScript, an iterable object refers to an object that implements the Symbol.iterator method. These objects can be iterated over using a for...of loop, or manipulated using other iterator methods. This article will provide an in-depth understanding of how to use JS's built-in iterable objects and give specific code examples.
Array is the most common iterable object in JavaScript. We can use a for...of loop to iterate through each element in the array, or use the array's forEach method to iterate.
Code example:
let arr = [1, 2, 3, 4, 5]; // 使用for...of循环遍历数组 for (let num of arr) { console.log(num); } // 使用数组的forEach方法遍历数组 arr.forEach(function(num) { console.log(num); });
Strings are also iterable objects in JavaScript. We can iterate through each character in the string through a for...of loop.
Code example:
let str = "hello"; // 使用for...of循环遍历字符串 for (let char of str) { console.log(char); }
Set is a collection of non-repeating elements and an iterable object. We can use a for...of loop to iterate through each element in the Set.
Code example:
let set = new Set([1, 2, 3]); // 使用for...of循环遍历Set for (let num of set) { console.log(num); }
Map is a collection of key-value pairs and an iterable object. We can use a for...of loop to iterate through each key-value pair in the Map.
Code example:
let map = new Map(); map.set('key1', 'value1'); map.set('key2', 'value2'); // 使用for...of循环遍历Map for (let [key, value] of map) { console.log(key, value); }
Generator is a function that can produce a series of values and is also an iterable object. We can use a for...of loop to iterate through the sequence of values generated by the Generator.
Code example:
function* generator() { yield 1; yield 2; yield 3; } // 通过Generator生成值序列 let gen = generator(); for (let num of gen) { console.log(num); }
In addition to the above built-in iterable objects, there are some other objects that are also iterable, such as TypedArray, NodeList, etc. We can iterate over them using the same method.
Summary:
In JavaScript, we can traverse various iterable objects through for...of loops, or use other iterator methods to operate. Mastering the use of these built-in iterable objects will make us more efficient and flexible when writing JavaScript code.
I hope this article can be helpful to readers. If you have any questions or suggestions, please leave a message for discussion. Thanks!
The above is the detailed content of Learn how to use JS's built-in iterable objects effectively. For more information, please follow other related articles on the PHP Chinese website!