需求需要循环中判断条件跳出当前循环
for循环写法不是很简洁
forEach不能跳出循环
1.跳出当前循环
const arr = [1, 2, 3, 4, 5];
for (const [index, item] of arr.entries()) {
if (item == 3) {
continue;
}
console.log(`Item: ${item},Index:${index} `);
}
//输出
Item: 1,Index:0
Home2.vue:366 Item: 2,Index:1
Home2.vue:366 Item: 4,Index:3
Home2.vue:366 Item: 5,Index:4
2.终止循环
const arr = [1, 2, 3, 4, 5];
for (const val of arr) {
if (val == 3) {
break;
}
console.log(`Item: ${val} `);
}
//输出
Item: 1
Home2.vue:366 Item: 2
3.遍历字符串
const arr = "这是一个数组";
for (const val of arr) {
if (val == 3) {
break;
}
console.log(`Item: ${val} `);
}
//输出
Item: 这
Home2.vue:366 Item: 是
Home2.vue:366 Item: 一
Home2.vue:366 Item: 个
Home2.vue:366 Item: 数
Home2.vue:366 Item: 组