Javascript中Array的4种遍历方式

let persons = [
  {id: 1, name: "Rick", age: 19},
  {id: 2, name: "Ashley", age: 19},
  {id: 3, name: "Jerry", age: 22},
  {id: 4, name: "Lucy", age: 25},
]

// for
const length = persons.length
for (let index = 0; index < length; index++) {
  if (index === 2) {
    return; // 可以中断遍历
  }
  p = persons[index]
  console.log(p.id, ":" ,p.name, index)
}

console.log('-----------')

// forEach
persons.forEach((p, index) => {
  if (index === 2) {
    return; // 不可以 中断遍历,这地方也不能使用 `break`。这个一个函数,函数在循环中
  }
  console.log(p.id, ":" ,p.name, index)
})

console.log('-----------')

// for...in
for (index in persons) {
  if (index === "2") {
    return; // 可以中断遍历
  }
  p = persons[index]
  console.log(p.id, ":" ,p.name, index)
}

// for...of
console.log('-----------')
for (p of persons) {
  if (p.id ===3 ) {
     return; // 可以中断遍历
  }
  console.log(p.id, ":" ,p.name)
}