Home > Web Front-end > JS Tutorial > Detailed explanation of the implementation principles of JavaScript class arrays and iterable objects

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

WBOY
Release: 2022-06-09 11:37:19
forward
2525 people have browsed it

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)}
Copy after login

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)}
Copy after login

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="https://img.php.cn/upload/article/000/000/067/05759c456d9c107fab3194b506d39378-4.png" 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>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>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)}
Copy after login

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

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

执行效果如下:

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)}
Copy after login

代码执行效果:

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)
Copy after login

代码执行效果如下:

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)
Copy after login

代码执行结果:

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

Array.from的完整语法:

Array.from(obj[, mapFunc, thisArg])
Copy after login

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

举个例子:

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

代码执行结果:

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template