for...of...
JavaScript for of
语句循环遍历可迭代对象的值。
它允许您循环遍历可迭代的数据结构,例如数组、字符串、映射、节点列表等:
遍历数组
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
遍历字符串
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}
For In 循环
JavaScript for in
语句循环遍历对象的属性:
语法
for (variable of iterable) {
// code block to be executed
}
const person = {fname:"Bill", lname:"Gates", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
// Bill Gates 25
例子解释
- for in 循环遍历 person 对象
- 每次迭代返回一个键 (x)
- 键用于访问键的值
- 键的值为 person[x]
For In 遍历数组
JavaScript for in
语句也可以遍历数组的属性:
语法
for (variable in array) {
code
}
实例
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
45
4
9
16
25
如果索引顺序很重要,请不要在数组上使用 for in。
索引顺序依赖于实现,可能不会按照您期望的顺序访问数组值。
当顺序很重要时,最好使用 for 循环、for of 循环或 Array.forEach()。
Array.forEach()
forEach()
方法为每个数组元素调用一次函数(回调函数)。
实例
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
注意,该函数采用 3 个参数:
- 项目值
- 项目索引
- 数组本身
上面的例子仅使用 value 参数。可以改写为:
实例
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;