Javascript 如何在Lodash中使用breakforEach()方法

Javascript 如何在Lodash中使用breakforEach()方法

Lodash _.forEach()方法遍历集合中的元素,并为每个元素调用迭代器。在本文中,我们将看到如何在Lodash库中中断forEach循环。

语法:

_.forEach( collection, [iterate = _.identity] )

参数:

此方法接受上述提到并下面描述的两个参数:

  • collection: 此参数保存要迭代的集合。
  • iterate: 每次迭代时调用的函数。

问题:

在Lodash中跳出forEach循环,使用 break 关键字无效。这样做会导致SyntaxError。

Javascript

<script>
    // Requiring the lodash library  
    const _ = require('lodash');
     
    _.forEach([1, 2, 3, 4], function (value) {
        if (value == 2) return false;
        console.log(value);
    });
</script>

输出:

SyntaxError: Illegal break statement 

解决方案: 所以根据这个我们知道我们不能在Lodash语法中使用break语句,所以如果我们要中断循环,我们必须从回调函数中返回false。

Javascript

<script>
    // Requiring the lodash library
    const _ = require('lodash');
     
    _.forEach([1, 2, 3, 4], function (value) {
        if (value == 3) {
            return false; // Breaks the forEach 
        }
        console.log(value);
    });
</script>

输出:

1
2

结论: 因此,要打破Lodash forEach循环,我们必须从回调函数中返回false。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程