Home > Article > Web Front-end > What are the new loops in es6?
es6 has a new loop statement: "for of" loop. The "for..of" statement can loop through the entire object and is a loop of a series of values produced by the iterator; the value of the "for..of" loop must be an iterable (iterable), and the syntax "for(current value of array){...}". The for-of loop not only supports arrays, but also supports most array-like objects; it also supports string traversal, and traverses strings as a series of Unicode characters.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
In the past, for loops and for in loops; and ES6 has new loops: for of loop: traverse (iterate, loop) the entire object.
ES6 adds a new for..of
loop, which is generated by the iterator A loop over a series of values. for..of
The value of the loop must be an iterable
.
var a = ["a", "b","c","d","e"] for(var idx in a){ console.log(idx) } // 0 1 2 3 4 for(var val of a){ console.log(val) } // a b c d e
for..in
Loop over the keys/indexes of array a
, for..of
ina
Loop over the value. [Related recommendations: javascript video tutorial, web front-end]
<span style="font-size: 18px;">ES6</span>
before Code var a = ["a", "b","c","d","e"] for(var val, ret, it = a[Symbol.iterator]();(ret=it.next()) && !ret.done){ val = ret.value console.log(val) } // a b c d e
At the bottom,
for..of
loop requests an iterator from iterable, and then repeatedly calls this iterator to assign the value it generates Give the loop an iteration variable.
JavaScript
The standard built-in values that default to iterable include:
Array
Strings
Generators
Collections/TypedArrays
for(var c of "hello"){ console.log(c) } // h e l l o
The native string value is cast to the equivalent String encapsulated object, which is an iterable
<span style="font-size: 18px;">for(XYZ of ABC)</span>
For XYZ
, this position can be either an assignment expression or a statement. Let’s look at an example of an assignment expression:
var o = {} for(o.a of [1,2,3]){ console.log(o.a) } o // {a:3} for({x:o.a} of [{x:1},{x:2},{x:3}]){ console.log(o.a) } o // {a:3}
Terminates the loop early through break
, continue
, return
.
Through the understanding of the underlying layer, for..of
to iterable
Request an iterator, and then call this iterator repeatedly to assign the value it produces to the loop iteration variable. Then I can customize a iterable
.
var o = { [Symbol.iterator](){ return this }, next(){ if(!val){ val = 1 }else{ val ++ } return {value:val, done:val== 6} } } for(var val of o[Symbol.iterator]()){ console.log(val) }
It can be seen that the custom iterator satisfies two conditions, [Symbol.iterator]
attribute, and the returned object has the next
method, The return value of the next
method must be in the form of {value:xx,done:xx}
. If done:true
is encountered, the loop ends.
Conclusion: The above is the entire content of the for..of loop, which can loop iterable objects.
To answer this question, let’s first take a look at the flaws of the three for loops before ES6:
但需要注意的是,for-of循环不支持普通对象,但如果你想迭代一个对象的属性,你可以用
for-in 循环(这也是它的本职工作)。
最后要说的是,ES6 引进的另一个方式也能实现遍历数组的值,那就是 Iterator。上个例子:
const arr = ['a', 'b', 'c']; const iter = arr[Symbol.iterator](); iter.next() // { value: 'a', done: false } iter.next() // { value: 'b', done: false } iter.next() // { value: 'c', done: false } iter.next() // { value: undefined, done: true }
前面的不多说,重点描述for-of
for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象。
for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:
window.onload=function(){ const arr = [55,00, 11, 22]; arr.name = "hello"; // Array.prototype.FatherName = 'FatherName'; /*for(let key in arr){ console.log('key='+key+',key.value='+arr[key]); }*/ /* arr.forEach((data) => {console.log(data);});*/ /* arr.forEach((data,index,arr) => {console.log(data+','+index+','+arr);});*/ /*for(let key of arr){ console.log(key); }*/ var string1 = 'abcdefghijklmn'; var string2 = 'opqrstuvwxyc'; const stringArr = [string1,string2]; for(let key of stringArr){ console.log(key); } for(let key of string1){ console.log(key); } }
结果:
现在,只需记住:
for-in循环用来遍历对象属性。
for-of循环用来遍历数据—例如数组中的值。
它同样支持Map和Set对象遍历。
Map和Set对象是ES6中新增的类型。ES6中的Map和Set和java中并无太大出入。
Set
和Map
类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set
中,没有重复的key。
要创建一个Set
,需要提供一个Array
作为输入,或者直接创建一个空Set
:
var s1 = new Set(); // 空Set var s2 = new Set([1, 2, 3]); // 含1, 2, 3
重复元素在Set中自动被过滤:
var s = new Set([1, 2, 3, 3, '3']); console.log(s); // Set {1, 2, 3, "3"}
通过add(key)
方法可以添加元素到Set
中,可以重复添加,但不会有效果:
var s = new Set([1, 2, 3]); s.add(4); s; // Set {1, 2, 3, 4} s.add(4); s; // Set {1, 2, 3, 4}
通过delete(key)
方法可以删除元素:
var s = new Set([1, 2, 3]); s; // Set {1, 2, 3} s.delete(3); s; // Set {1, 2}
Set对象可以自动排除重复项
var string1 = 'abcdefghijklmn'; var string2 = 'opqrstuvwxyc'; var string3 = 'opqrstuvwxyc'; var string4 = 'opqrstuvwxyz'; const stringArr = [string1,string2,string3,string4]; var newSet = new Set(stringArr); for(let key of newSet){ console.log(key); }
结果:
Map对象稍有不同:内含的数据由键值对组成,所以你需要使用解构(destructuring)来将键值对拆解为两个独立的变量:
for (var [key, value] of phoneBookMap) { console.log(key + "'s phone number is: " + value); }
示例
var m = new Map([[1, 'Michael'], [2, 'Bob'], [3, 'Tracy']]); var map = new Map([['1','Jckey'],['2','Mike'],['3','zhengxin']]); map.set('4','Adam');//添加key-value map.set('5','Tom'); map.set('6','Jerry'); console.log(map.get('6')); map.delete('6'); console.log(map.get('6')); for(var [key,value] of map) { console.log('key='+key+' , value='+value); }
结果:
The above is the detailed content of What are the new loops in es6?. For more information, please follow other related articles on the PHP Chinese website!