说明
ES6 借鉴 C++、Java、C# 和 Python 语言,引入了for…of循环,作为遍历所有数据结构的统一的方法。
for…of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、 Generator 对象,以及字符串。
相较于其他循环
const arr = new Array('kangkang', 'hello', 'world', 'sun')
// 1.for循环比较繁琐
for (let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
// 2.for each循环不能终止,只能遍历数据不可以使用continue、break
arr.forEach((itm,ind) => {
if (itm === "Banana") {
break;
}
//Illegal break statement at Array.forEach
console.log(itm,ind)
})
// 3.for in循环索引是字符串型的数字,因而不能直接进行几何运算
// 遍历顺序可能不是实际的内部顺序
// for in会遍历数组所有的可枚举属性,包括原型。例如的原型方法
Array.prototype.istrue = function (value) { return true; }
var a = [1, 2];
for (var i in arr) {
console.log(i);
}
for (var i in a) {
console.log(a[i]);
}
特点
// for of 循环输出属性值,且只遍历输出数字属性(即通过下标可以查找),而且可以使用 break 和 continue
const arr = new Array('kangkang', 'hello', 'world', 'sun')
for (const val of arr) {
if (val === 'hello') {
// continue
// brank
}
console.log(val);
}
// for of循环是无法遍历对象的
const userMsg = {
name:"Tom",
age:12
}
for (const per of userMsg ) {
console.log(per) //userMsg is not iterable
}
// for of 循环用来遍历可迭代对象,可迭代对象指的是有iterable接口的,其中有一个next()方法,可手动调用next()方法遍历数组,而for of循环 会自动帮我执行这个给过程
// 使用for of 循环 返回计算结果
function sum(){
let total = 0;
for (let num of arguments) {
total = total + num;
}
console.log(total)
return total;
}
sum(10, 23, 45);//78
// 也可用于字符串
const str = "Bommst"
for (let temp of str) {
console.log(temp);// B o m m s t
}
// // for of 遍历 nodelist(节点列表)
const list = document.querySelectorAll(".main");
for (let dom of list) {
console.log(dom)
}
总结
一个数据结构只要部署了Symbol.iterator属性,就被视为具有 iterator 接口,就可以用for…of循环遍历它的成员。也就是说,for…of循环内部调用的是数据结构的Symbol.iterator方法。
后期更新iterator的相关内容