发布时间:2024-04-11 21:30:01
JS for of 循环是 ECMAScript6 中新添加的一个循环方式,与 for in 循环类似,也是普通 for 循环的一种变体。使用 for of 循环可以轻松的遍历数组或者其它可遍历的对象,例如字符串、对象等。
for (variable of iterable) {
// 要执行的代码
}
{ }
中使用这个变量来进行一系列操作;iterable 为要遍历的内容,在每次循环中,会将 iterable 中的一个值赋值给变量 variable,直到 iterable 中的所有值都遍历完。// 定义一个数组 var arr = ['a', 'b', 'c', 'd', 'e', 'f']; // 使用 for of 循环遍历数组中的每个元素 for (var value of arr) { document.write(value + ", "); } document.write("运行结果:
"); // 定义一个字符串 var str = "Hello World!"; // 使用 for of 循环遍历字符串中的每个字符 for (var value of str) { document.write(value + ", "); } document.write("
"); // 定义一个对象 var obj = {"name": "Clark", "surname": "Kent", "age": "36"}; // 使用 for of 循环遍历对象中的所有属性 for(var value in obj) { document.write(value + ", "); }
a, b, c, d, e, f,
H, e, l, l, o, , W, o, r, l, d, !,
name, surname, age,
Copyright © 2009-2023 www.365tools.cn All Rights Reserved. 365工具网 版权所有 赣ICP备2023013700号-2