Skip to content

Latest commit

 

History

History
58 lines (51 loc) · 1.4 KB

8.for-of-loop.md

File metadata and controls

58 lines (51 loc) · 1.4 KB

for of

// for循环 可读性差、繁琐
const fruits = ['apple', 'banana', 'orange', 'mango'];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// forEach 不能终止或者跳过
fruits.forEach(fruit => console.log(fruit));

// for in 遍历对象上的可枚举属性 如果
fruits.describe = 'my favourite fruits'
// describe的内容也会遍历出来
for (let index in fruits) {
    console.log(fruits[index]);
}

// for of 支持终止打断,fruit直接就是属性值
for(fruit of fruits){
	console.log(fruit);
}

使用实例

可以遍历可迭代对象,可迭代对象就是部署了迭代器接口 iterable,很多内置的数据结构提供了内置的遍历器接口。比如 array 或者 map

for(let [index,fruit] of fruits.entries()){
	console.log(`${fruit} ranks ${index+1} in my favorite fruits`);
}

for of 支持循环数组,字符串,map,set,arguments等数据结构,但是目前不支持对象

// 数组
function sum() {
    let total = 0;
    for (let num of arguments) {
        total += num;
    }
    console.log(total);
}
sum(23, 432, 65, 767, 23);

// 字符串
let name = 'laravel';
for (let char of name) {
    console.log(char);
}

// nodelist
const lis = document.querySelectorAll('li');
for (let li of lis) {
    li.addEventListener('click', function () {
        this.classList.toggle('completed');
    });
}