在 TypeScript 中使用索引遍历数组

使用 forEach() 方法迭代具有索引的数组,例如 arr.forEach((element, index) => {})。 回调函数采用的第二个参数是数组中元素的索引。

const arr: string[] = ['one', 'two', 'three'];

arr.forEach((element, index) => {
  // ?️ one 0, two 1, three 2
  console.log(element, index);
});

我们传递给 Array.forEach 方法的函数会针对数组中的每个元素进行调用。

回调函数传递以下 3 个参数:

  1. 数组中的当前元素。
  2. 数组中元素的索引。
  3. 我们调用 forEach() 方法的数组。

forEach 方法返回 undefined,因此它用于改变外部变量。

如果我们需要使用索引遍历数组,但每次迭代都返回一个值,请改用 Array.map 方法。

const arr: string[] = ['one', 'two', 'three'];

const result = arr.map((element, index) => {
  return element + index;
});

// ?️ ['one0', 'two1', 'three2']
console.log(result);

我们传递给 map() 方法的函数会调用数组中的每个元素,并传递与 forEach() 相同的参数。

如果在满足条件时必须使用 break 关键字跳出循环,请改用基本的 for 循环。

const arr: string[] = ['one', 'two', 'three'];

for (let index = 0; index < arr.length; index++) {
  // ?️ one 0, two 1
  console.log(arr[index], index);

  if (index === 1) {
    break;
  }
}

基本的 for 循环并不像使用 forEach() 那样优雅,但使我们能够使用 break 关键字在满足条件时跳出循环。