javascript中for...of循环解析
墨初 Web前端 1434阅读
在javascript脚本代码,for...of循环是一种用于遍历数组中元素的一种语法,它可以帮助我们轻松的提取数组中的每个元素,
for...of基本语法
for( a of arr){
// 每个元素的执行代码
}
参数:
arr:一个可以迭代的对象,数组,字符串等
element:当前遍历迭代对象中的元素
for...of示例
1、数组处理
const arr = ['php', 'js', 'java','73so.com'];
for(let a of arr){
console.log(a);
}
2、处理字符串
const str = 'https://www.73so.com';
for(a of str){
console.log(a);
}
3、遍历 Map
const arr = new Map([
['name','mochu'],
['host','https://www.73so.com']
]);
for(const [key,value] of arr){
console.log(key);
console.log(value);
}
4、遍历Set
const set = new Set([1, 2, 3]);
// https://www.73so.com
for (const a of set) {
console.log(a);
}
注意:
1、for...of 可以使用break与continue来控制循环流程与for循环一样
2、for...of 循环数组中的每个元素
3、for...of 可以用于Set与Map等迭代对象
4、for...fo 可以访问数组元素索引,参考本站相关文章。