遍历(For of Loop Examples)

 Array.prototype.first = function () {
    return this[0]
  }
  const fruits = ['Apple', 'Banana', 'Orange', 'Mango']
  fruits.desc = 'My favorite fruits'
  
  
  //for循环的缺点,结构复杂,可读性不高
  for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i])
  }
  //Apple Banana Orange Mango

  //forEach的缺点是不能终止与跳过
  fruits.forEach(fruit => console.log(fruit))
  //Apple Banana Orange Mango

  //需要注意的是forin遍历的是对象上可枚举属性
  for (let index in fruits) {
    console.log(fruits[index])
  }
  //Apple Banana Orange Mango My favorite fruits ƒ (){return this[0]}

  //因此为了解决以上的问题,ES6提供了forOf
  for (let fruit of fruits) {
    if(fruit==='Banana'){
      break;
    }
    console.log(fruit)
  }
  //Apple
for of 的应用
//遍历字符串
  const string = 'ABCDEF'
  for (let str of string) {
    console.log(str)
  }
  //A B C D E F

  //遍历arguments
  function list(){
    for(let arg of arguments){
       console.log(arg)
    }
  }
  list(1,2,3,4,5)
  //1 2 3 4 5

    //遍历数组
    for(let [index,fruit] of fruits.entries()){
      console.log(`${index++}---->${fruit}`)
    }
  /**
   * 0---->Apple
   * 1---->Banana
   * 2---->Orange
   * 3---->Mango
   */
遍历DOMList


  • Apple
  • Banana
  • Orange
  • Mango
点击事件

你可能感兴趣的:(遍历(For of Loop Examples))