js 中的 for...of... for..in...

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值