我是靠谱客的博主 不安胡萝卜,这篇文章主要介绍forEach 中跳过本次循环和终止循环,现在分享给大家,希望可以做个参考。

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

使用 forEach 方法来遍历数组是最常使用的一种方式,但在实际开发中通常通过会有跳过本次循环和终止循环的情形,首先想到的应该是使用 continue 和 break 关键字,但无奈这两个关键字在 forEach 中都无法使用(写了会报错错误语法),此时就该寻找其它解决方法。

1. forEach 中跳过本次循环

const arr = [1, 2, 3, 4, 5];

arr.forEach(function (item) {
	console.log(item);
});
// result:
// 1
// 2
// 3
// 4
// 5

使用 return 语句实现 continue 关键字效果。

const arr = [1, 2, 3, 4, 5];

arr.forEach(function (item) {
	if (item === 3) {
		return;
	}
	console.log(item);
});
// result:
// 1
// 2
// 4
// 5

关于 return、return true、return false 的区别。return 可以看成是 return undefined,此时 return 和 return false 的写法都可以看成是返回一个 false 的结果(undefined 转换为布尔值就是 false),只有 return true 的写法时返回一个 true 的结果。了解这一点对于区分 forEach、 some 和 every 至关重要。

在 forEach 方法中,不管 return 返回的结果是 true 还是 false,forEach 都会跳过本次循环执行下一次循环。这就导致在 forEach 中无法直接终止循环(定义计数变量除外)。而 some 和 every 方法可以终止循环。

2. some() 实现遍历数组

在 some 方法中,return 返回的结果为 true 表示终止循环,return 返回结果为 false 表示跳过本次循环。

  • return 返回结果为 true 示例代码:

    const arr = [1, 2, 3, 4, 5];
    
    arr.some(function (item) {
    	console.log(item);
    	return item === 3;
    });
    // result:
    // 1
    // 2
    // 3
    
  • return 返回结果为 false 示例代码:

    const arr = [1, 2, 3, 4, 5];
    
    arr.some(function (item) {
    	if (item === 2) {
    		return;
    	}
    	console.log(item);
    });
    // result:
    // 1
    // 3
    // 4
    // 5
    

3. every() 实现遍历数组

与 some 方法恰好相反,在 every 方法中,return 返回的结果为 false 表示终止循环,return 返回结果为 true 表示跳过本次循环。

  • return 返回结果为 false 示例代码:

    const arr = [1, 2, 3, 4, 5];
    
    arr.every(function (item) {
    	console.log(item);
    	return item !== 3;
    });
    // result:
    // 1
    // 2
    // 3
    
  • return 返回结果为 true 示例代码:

    const arr = [1, 2, 3, 4, 5];
    
    arr.every(function (item) {
    	if (item === 2) {
    		return true;        // 这个地方如果换成 return 会有不一样的结果。
    	}
    	console.log(item);
    	return item !== 5;
    });
    // result:
    // 1
    // 3
    // 4
    // 5
    

转载于:https://my.oschina.net/dkvirus/blog/1527345

最后

以上就是不安胡萝卜最近收集整理的关于forEach 中跳过本次循环和终止循环的全部内容,更多相关forEach内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(264)

评论列表共有 0 条评论

立即
投稿
返回
顶部