"Continue" 在 Lodash forEach 中
"Continue" in Lodash forEach
我在查看 Underscore 和 Lodash 库之间的差异时发现了一个关于 _.each / _.forEach 的问题。
在 Underscore 中,_.each 函数无法跳出循环。当使用 return false 时,它仅作为 "continue" 语句起作用。 (这是我的预期功能)=它强制进行下一次循环迭代,跳过中间的任何代码。
另一方面,在 Lodash 中,returning false 告诉 _.forEach() 本次迭代将是最后一次。有没有办法让 "continue" 行为在 Lodash 中也起作用?
谢谢。
In Lodash, on the other hand, returning false tells _.forEach() that this iteration will be the last. Is there a way to make the "continue" behavior also functional in Lodash?
你可以return true
,或者只是一个return
(returns undefined
),这个值不同于needed false
对于 "exit iteration early by explicitly returning false
."
_.forEach([1, 2, 3, 4, 5], function (a) {
if (a < 3) return; // continue
console.log(a);
if (a > 3) return false; // break
// return undefined; // continue, undefined is the standard value of ending a function
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
我在查看 Underscore 和 Lodash 库之间的差异时发现了一个关于 _.each / _.forEach 的问题。
在 Underscore 中,_.each 函数无法跳出循环。当使用 return false 时,它仅作为 "continue" 语句起作用。 (这是我的预期功能)=它强制进行下一次循环迭代,跳过中间的任何代码。
另一方面,在 Lodash 中,returning false 告诉 _.forEach() 本次迭代将是最后一次。有没有办法让 "continue" 行为在 Lodash 中也起作用?
谢谢。
In Lodash, on the other hand, returning false tells _.forEach() that this iteration will be the last. Is there a way to make the "continue" behavior also functional in Lodash?
你可以return true
,或者只是一个return
(returns undefined
),这个值不同于needed false
对于 "exit iteration early by explicitly returning false
."
_.forEach([1, 2, 3, 4, 5], function (a) {
if (a < 3) return; // continue
console.log(a);
if (a > 3) return false; // break
// return undefined; // continue, undefined is the standard value of ending a function
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>