TypeScript forEach 循环

注意: 如果您是 TypeScript 新手,请先查看我们的 TypeScript 入门 教程。


TypeScript forEach() 方法会对数组中的每个元素执行一个函数。

这是一个 forEach() 方法的简单示例。您可以阅读本教程的其余部分以了解更多信息。

示例

let nums: number[] = [1, 2, 3, 4];

// Function that prints the number passed to it
function printNumber(arg: number): void {
    console.log(arg);
}

// Use forEach() to execute printNumber()
// on each element in the numbers array 
nums.forEach(printNumber);

// Output: 
// 1
// 2
// 3
// 4

在这里,我们使用 forEach() 方法对 nums[] 数组的每个元素执行 printNumber() 函数。


TypeScript forEach()

forEach() 方法的语法是:

array.forEach(function(currentValue, index?, arr?))

这里,

  • function - 要对数组的每个元素运行的函数。
  • currentValue - 数组的当前元素。
  • index - 当前元素的索引(可选)。
  • arr - 正在进行循环的数组(可选)。

更新数组元素

您可以使用 forEach() 方法来更新数组元素。例如:

let students: string[] = ["John", "Sara", "Jack"];

function addText(item: string, index: number, arr: string[]) {
    // Add "Hello" to the array elements
    arr[index] = "Hello" + item;
}

// Use forEach() to execute addText()
// on each element of the students array
students.forEach(addText);

console.log(students);

输出

[ 'HelloJohn', 'HelloSara', 'HelloJack' ]

在这里,addText() 函数被传递给 forEach(),并对 students[] 数组的每个元素执行。

该函数通过向数组的每个元素添加 "Hello" 来直接修改 students[] 数组。


使用箭头函数实现 forEach

您可以使用箭头函数与 forEach() 方法。例如:

let students: string[] = ["John", "Sara", "Jack"];

// Use arrow function with forEach()
students.forEach(element => {
    console.log(element);
});

输出

John
Sara
Jack

在上面的示例中,forEach() 方法与箭头函数一起用于遍历 students[] 数组。

在这里,students[] 数组的每个元素都被传递给箭头函数,然后该函数将该元素打印到控制台。


更多关于 forEach()

模仿 forEach() 中的 continue

与传统循环不同,您不能在 forEach() 回调中使用 continue 语句。

要跳过某些迭代,请使用条件语句和 return 提前退出当前回调。例如:

let nums: number[] = [1, 2, 3, 4, 5];

// Use forEach() to only print odd numbers
nums.forEach((value: number) => {

    // Check if value is even
    if (value % 2 === 0) {
        return; // Skip iteration
    }
    
    // Prints only odd values
    console.log(value);
});

输出

1
3
5

在这里,回调函数检查当前数组元素是否为偶数。如果是,return 语句将跳过该迭代。

因此,只有当 value 为奇数时,才会执行 console.log(value);

使用 Set 的 forEach()

您可以使用 forEach() 方法来遍历 Set 的元素。例如:

// Create a set of numbers
let numbersSet: Set<number> = new Set<number>([1, 2, 3]);

function printItems(item: number): void {
    console.log(item);
}

// Use forEach() to execute printItems()
// on each element of the numbersSet set
numbersSet.forEach(printItems);

输出

1
2
3

在这里,我们使用 forEach() 方法对 numbersSet 集合的每个元素调用 printItems() 函数。

使用 Map 的 forEach()

您可以使用 forEach() 方法来遍历 Map 元素。例如:

// Create a map where the key is of string type
// And the value is of either string or number type

let employeeInfo: Map<string, string | number> = new Map<string, string | number>();

// Insert elements to map
employeeInfo.set("name", "Jack");
employeeInfo.set("age", 27);

function printInfo(value: string | number, key: string) {
    console.log(`${key} : ${value}`);
}

// Use forEach() to execute the printInfo() function
// on each items of the employeeInfo map
employeeInfo.forEach(printInfo);

输出

name : Jack
age : 27
forEach() 与 for 循环的比较

当您需要将函数应用于数组中的每个元素并倾向于更简洁、更函数式的编程方法时,请使用 forEach()

当您需要对迭代过程进行详细控制时,例如修改循环计数器,请使用 for 循环。

让我们看下面的例子,我们在其中使用了 foreach()for 来遍历数组。

let fruits: string[] = ["apple", "banana", "cherry"];

// Loop using forEach()
console.log("Using forEach():");

fruits.forEach(function(fruit: string): void {
    console.log(fruit);
});

// Loop using a for loop
console.log("\nUsing a for loop:");

for (let i: number = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

输出

Using forEach():
apple
banana
cherry

Using a for loop:
apple
banana
cherry

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战