Home >Web Front-end >JS Tutorial >Detailed 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.
[Related recommendations: javascript video tutorial, web front-end】
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:
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:
#This proves that there is an iterable gap between ordinary objects and arrays. We call iterative The object is an iterable object.
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:
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). for ... of
will continuously call the next()
method of the iterator to obtain the next element. 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 onlynext()
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)}
这对于代理对(UTF-16
扩展字符)同样是有效的:
let str = '...'for(let c of str){ console.log(c)}
执行效果如下:
并非只有for...of
语句能够使用迭代器,我们还可以显式的调用迭代器:
let str = '12345'let itr = str[Symbol.iterator]()while(true){ let result = itr.next() if(result.done)break; console.log(result.value)}
代码执行效果:
以上代码执行了遍历字符串字符的操作,是不是觉得可迭代对象就没有这么神秘了!
类数组和可迭代在遍历功能上非常相似,都可以方便的方式内部元素,但是二者仍然有明显的区别:
iterable
可迭代对象:实现了Symbol.iterator
的对象;array-like
类数组对象:具有数字索引,并且有length
属性;字符串就是一个即使类数组又是可迭代的对象。
可迭代和类数组对象通常都不是数组,如果我们想把一个可迭代或者类数组对象转为数组,需要使用Array.from
方法。
使用Array.from
将字符串转为数组:
let str = '123'let arr = Array.from(str)console.log(arr)
代码执行效果如下:
把自定义的类数组对象转为数组:
let obj = { 0:'0', 1:'1', 2:'2', length:3}let arr = Array.from(obj)console.log(arr)
代码执行结果:
Array.from
的完整语法:
Array.from(obj[, mapFunc, thisArg])
mapFunc
方法会在生成数组之前对每个可迭代或类数组元素调用,如果mapFunc
是一个成员方法,可以使用thisArg
提供this
指针。
举个例子:
let str = '12345'let arr = Array.from(str,itm=>+itm)console.log(arr)
代码执行结果:
这里通过映射函数,将本应该生成字符数组转为数字数组。
for...of
语法的对象被称为可迭代对象
Symbol.iterator
方法的对象Symbol.iterator
方法返回了一个迭代器;next
方法,该方法返回下一个元素的值;next
方法返回值需要满足格式{done:Boolean,value:nextVal}
,当done:true
时,迭代结束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!