foreach循环语句

admin 40 0

在编程中,`foreach`循环是一种常用的循环结构,用于遍历数组或集合中的每个元素,以下是几种常见编程语言中`foreach`循环的示例:

1. **Java**

List<String> list = Arrays.asList("apple", "banana", "cherry");
for (String fruit : list) {
    System.out.println(fruit);
}

2. **Python**

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

3. **JavaScript**

let fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
    console.log(fruit);
});

4. **C#**

List<string> fruits = new List<string> { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

在这些示例中,`foreach`循环用于遍历数组或列表中的每个元素,并将当前元素赋值给变量(如`fruit`),循环体中的代码可以对当前元素进行操作。