for..of 循环在 JavaScript 中的用法
for..of 循环是一种用于遍历可迭代对象的 JavaScript 循环语句。可迭代对象可以是数组、字符串、映射或 Set。
语法
for (variable of iterable) { // 代码块}
其中:
- variable:用来存储可迭代对象中每个元素的变量。
- iterable:要遍历的可迭代对象。
用法
for..of 循环遍历可迭代对象,每次迭代都会将当前元素的值分配给 variable 变量。循环一直持续到可迭代对象中的所有元素都被遍历完毕。
示例:遍历数组
const arr = [1, 2, 3, 4, 5];for (const item of arr) { console.log(item); // 输出:1 2 3 4 5}
示例:遍历字符串
const str = "Hello";for (const char of str) { console.log(char); // 输出:H e l l o}
注意:
- for..of 循环仅用于遍历可迭代对象,不能用于遍历普通的对象。
- for..of 循环不会修改可迭代对象本身。
- for..of 循环中可以使用 break 和 continue 语句来控制循环流。
以上就是js中forof的用法的详细内容,更多请关注css网站其它相关文章!