ES6 for of的使用

与其他遍历方法的比较

const fruits = ['apple','coconut','mango','durian'];
//for循环数组,通过下标取得每一项的值
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}
//数组的forEach方法,相对for循环语法更简单
fruits.forEach(fruit => {
    console.log(fruit);
})

//forEach有个问题是不能终止循环
fruits.forEach(fruit => {
    if(fruit === 'mango' ){
        break;                        //Illegal break statement
    }
    console.log(fruit);
})
//for...in循环,遍历数组对象的属性,MDN不推荐使用for...in遍历数组
//for...in循环会打印出非数字属性
const fruits = ['apple','coconut','mango','durian'];
fruits.fav = 'my favorite fruit';

for(let index in fruits){
    console.log(fruits[index]);   //...my favorite fruit
}
const fruits = ['apple','coconut','mango','durian'];
fruits.fav = 'my favorite fruit';

//ES6中的for...of循环,遍历属性值
for(let fruit of fruits){
    console.log(fruit);
}

//支持终止循环,也不会遍历非数字属性
for(let fruit of fruits){
    if(fruit === 'mango' ){
        break;
    }
    console.log(fruit);      //apple coconut durian
}

应用场景

//arguments是个类数组对象,通常先要将其转换为数组才能遍历,但for...of可以直接遍历
function sum() {
    let sum = 0
    for(let num of arguments){
        sum += num
    }
    console.log(sum);        //15
}

sum(1,2,3,4,5)
let name = 'Asher';
for (let char of name){
    console.log(char);         //A s h e r
}
//遍历nodelists,效果如下图


    
  • yoga
  • boxing
  • press

你可能感兴趣的:(ES6 for of的使用)