JavaScript loops and iteration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// for...in 示例(遍历对象)
const person = { name: 'Alice', age: 25 };
for (let key in person) {
console.log(key + ': ' + person[key]);
}
// 输出:
// name: Alice
// age: 25

// for...in 示例(遍历数组)
const arr = ['a', 'b', 'c'];
for (let index in arr) {
console.log(index + ': ' + arr[index]);
}
// 输出:
// 0: a
// 1: b
// 2: c

// for...of 示例(遍历数组)
for (let value of arr) {
console.log(value);
}
// 输出:
// a
// b
// c

// for...of 不能直接遍历普通对象
// 下面代码会报错
// for (let value of person) {
// console.log(value);
// }

JavaScript loops and iteration
https://www.hardyhu.cn/2024/11/26/JavaScript-loops-and-iteration/
Author
John Doe
Posted on
November 26, 2024
Licensed under