for

经典和著名的 for 循环迭代数组中的每个项目。
for 循环遍历一个代码块多次:

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

for 使用 3 个表达式:

  • 初始化 - 使用只能执行一次的起始值初始化循环变量。
  • 条件 - 指定循环应该停止循环
  • 最终表达式 - 在每个循环执行结束时执行。它用于增加索引。
如何在 JavaScript 中循环遍历数组

在 JavaScript 中循环遍历数组和任何其他对象是许多程序员最常遇到的常见问题。

在 JavaScript 中有几种方法可以循环遍历数组。

while

只要指定条件为真,while 就会循环执行代码块:

let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}

在给定的示例中,只要变量 (i) 小于 10,循环中的代码就会一遍又一遍地运行。

我们可以在 while 循环中使用 break 和 continue。
但是当我们使用 while 循环时,我们应该考虑下一次迭代的增量。
如果不这样做,则可能会导致无限循环。

forEach()

for 和 for/in 循环的替代方法是Array.prototype.forEach()。
forEach() 对数组中的每个索引元素运行一个函数。
从 index[0] 开始,一个函数将在 index[0]、index[1]、index[2] 等处被调用……forEach() 将让我们以与 for 循环几乎相同的方式遍历数组:

let array = [{
    id: 1,
    name: 'John',
    age: 12
  },
  {
    id: 2,
    name: 'Jane',
    age: 14
  },
  {
    id: 3,
    name: 'Martin',
    age: 13
  },
  {
    id: 4,
    name: 'Katie',
    age: 17
  },
  {
    id: 5,
    name: 'Louis',
    age: 11
  }
];
array.forEach(function (profile, index, arr) {
  console.log(`Index: ${index}, Name: ${profile.name}`);
});

forEach() 不是函数式的,因为它作为输入参数的函数不应该返回值,因此不能被视为纯函数。

for...in

for...in 循环遍历对象的属性。
它是迭代对象最常用和最直接的方法之一:

let person = {
  fname: "John",
  lname: "Doe",
  age: 25
};
for (let i in person) {
  console.log(person[i] + " ");
}

map()

map() 方法使用为每个数组元素调用函数的结果创建一个新数组。

const array = [2, 3, 5, 7];
console.log(array.map(el => el * 2));

乍一看,map() 方法与 forEach() 方法有相似之处,因为它也会为每个数组元素调用一次回调函数。
不同之处在于 map() 根据回调函数结果创建并返回新数组。

日期:2020-06-02 22:16:22 来源:oir作者:oir