search
HomeWeb Front-endJS TutorialDetailed explanation of the implementation principles of JavaScript class arrays and iterable objects

This article brings you relevant knowledge about javascript, which mainly introduces the implementation principles of class arrays and iterable objects, including constructing the objects themselves into iterators and Strings Let’s take a look at iterators and other related content. I hope it will be helpful to everyone.

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

[Related recommendations: javascript video tutorial, web front-end

Iterable object )

Array is a special object, and its difference from ordinary objects is not only the sequential access and storage of elements. Another important difference is that arrays are iterable, that is, you can use the for ... of statement to access (iterate) all elements.

We can simply do a small experiment:

let arr = [1,2,3,4,5]for(let val of arr){
    console.log(val)}

Code execution results:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

The above code simply uses an array Iteration feature, when we access array elements, we do not have to use the subscript of the element.

What happens if we use the for ... of statement on a normal object?

let obj = {
    name:'xiaoming',
    age:12,}for(let para of obj){ //代码会报错
    console.log(para)}

The execution effect is as follows:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

#This proves that there is an iterable gap between ordinary objects and arrays. We call iterative The object is an iterable object.

Symbol.iterator

If we want an object to be iterable, we must add a method named Symbol.iterator to the object (an inner function that specifically makes the object iterable). Build Symbol).

Method functions include:

  1. When using for ... of loop to iterate an object, the Symbol.iterator method will be called , this method must return an iterator (an object with a next() method).
  2. After getting the iterator, for ... of will continuously call the next() method of the iterator to obtain the next element.
  3. next()The content returned by the method must conform to the format: {done:Boolean,value:any}, when done:true , the loop ends, otherwise value is the next value.

Iterator:

The iterator is a concept borrowed from C and other languages. The principle of the iterator is like a pointer, which points to a data collection. For an element in , you can get the element it points to, or you can move it to get other elements. Iterators are similar to the expansion of subscripts in arrays. Various data structures are available, such as linked lists (List), sets (Set), and maps (Map). The corresponding iterator.

The iterator in JS is specially designed for the operation of traversal. The iterator obtained each time always points to the first element initially, and the iterator has only next() behavior until the last element of the data set is obtained. We cannot flexibly move the position of the iterator, so the task of the iterator is to traverse the elements in the data set in a certain order.

Implementing an iterable object:

let obj = {
    from:1,
    to:5,}obj[Symbol.iterator] = function(){
    //返回一个迭代器
    return {
        current:this.from,
        last:this.to,
        next(){
            if(this.current<this.last><p>Code execution effect: </p>
<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/067/05759c456d9c107fab3194b506d39378-4.png?x-oss-process=image/resize,p_40" class="lazy" alt="Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects"></p>
<p>Note that although the above objects can be iterated , however, the material used for iteration is not an object, but the iterator (also an object) returned by <code>Symbol.iterator</code>. </p>
<h2 id="Construct-the-object-itself-into-an-iterator">Construct the object itself into an iterator</h2>
<p>The above code constructs a built-in function <code>Symbol.iterator()</code>, which returns an iterator object. We can also use another way to implement iterators: make the object itself an iterator: </p>
<pre class="brush:php;toolbar:false">let obj = {
    from:1,
    to:5,
    [Symbol.iterator](){
        this.current = this.from;
        return this;//返回对象本身
    },
    next(){//给对象添加一个next方法
        if(this.current<this.to><p>The code execution effect is the same as the picture above. </p>
<blockquote><p> Although the code is more concise by doing this, since no new iterable object is generated, we have no way to execute two <code>for ... of</code> loop iterations at the same time. One object, but two parallel iterations on the same object are very rare. </p></blockquote>
<p>We can summarize the concept of iterable objects: </p>
<p>The so-called iterable objects are ordinary objects with one more method named <code>Symbol.iterator</code> Object, this method returns an iterator. </p>
<p>Or, an object with <code>Symbol.iterator</code> and <code>next</code> method is also an iterable object. </p>
<h2 id="String-is-also-iterable">String is also iterable </h2>
<p>Both arrays and strings can be iterated, we can easily use the <code>for...of</code> statement to iterate the characters in the array element:</p>
<pre class="brush:php;toolbar:false">let str = '123'for(let c of str){
    console.log(c)}

这对于代理对(UTF-16扩展字符)同样是有效的:

let str = '...'for(let c of str){
    console.log(c)}

执行效果如下:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

String的迭代器

并非只有for...of语句能够使用迭代器,我们还可以显式的调用迭代器:

let str = '12345'let itr = str[Symbol.iterator]()while(true){
    let result = itr.next()
    if(result.done)break;
    console.log(result.value)}

代码执行效果:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

以上代码执行了遍历字符串字符的操作,是不是觉得可迭代对象就没有这么神秘了!

类数组对象和可迭代对象

类数组和可迭代在遍历功能上非常相似,都可以方便的方式内部元素,但是二者仍然有明显的区别:

  1. iterable可迭代对象:实现了Symbol.iterator的对象;
  2. array-like类数组对象:具有数字索引,并且有length属性;

字符串就是一个即使类数组又是可迭代的对象。

可迭代和类数组对象通常都不是数组,如果我们想把一个可迭代或者类数组对象转为数组,需要使用Array.from方法。

Array.from

使用Array.from将字符串转为数组:

let str = '123'let arr = Array.from(str)console.log(arr)

代码执行效果如下:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

把自定义的类数组对象转为数组:

let obj = {
    0:'0',
    1:'1',
    2:'2',
    length:3}let arr = Array.from(obj)console.log(arr)

代码执行结果:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

Array.from的完整语法:

Array.from(obj[, mapFunc, thisArg])

mapFunc方法会在生成数组之前对每个可迭代或类数组元素调用,如果mapFunc是一个成员方法,可以使用thisArg提供this指针。

举个例子:

let str = '12345'let arr = Array.from(str,itm=>+itm)console.log(arr)

代码执行结果:

Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

这里通过映射函数,将本应该生成字符数组转为数字数组。

总结

  1. 可以使用for...of语法的对象被称为可迭代对象
  2. 可迭代对象是在普通对象的基础上实现了Symbol.iterator方法的对象
  3. Symbol.iterator方法返回了一个迭代器;
  4. 迭代器包含一个next方法,该方法返回下一个元素的值;
  5. next方法返回值需要满足格式{done:Boolean,value:nextVal},当done:true时,迭代结束
  6. Array.from可以把类数组和可迭代对象转为数组;

【相关推荐:javascript视频教程web前端

The above is the detailed content of Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment