ES6 forof解析

说明

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的相关内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值