首页 Vue 🍺

Vue arr.forEach 跳出循环的多种方式

起因

for 循环中跳出循环是使用 break 可是如果在 forEach 中使用 break 跳出循环是会报错的,而且即使使用 return 也无法跳出循环。那么我们使用 forEach 遍历数组的时候该如何跳出循环呢

使用 try...catch 捕获异常

判断元素是否在数组中

itemInArray(arr,target){
    try{
        arr.forEach(function(item){
            if(item==target){
                throw new Error("");
            }
        })
    }catch(e){
        return true;
    }
    return false;
}

使用 arr.some()

some:当内部出现 return true 时跳出整个循环

var arr=[1,2,3,4,5]
this.arr.some((element) => {
    if (element == 3) {
        return true;
    }
    console.log(element)
});

使用 arr.every()

every:当内部出现 return false 时跳出整个循环 刚好与上面的 some 相反

var arr=[1,2,3,4,5]
this.arr.every((element) => {
    if (element == 3) {
        return false;
    }
    console.log(element)
    return true;
});



文章评论

目录