如何在underscore.js中中断_.each函数


无法从each方法中中断。它复制原生forEach方法的行为,而原生forEach不会提供跳出循环(以外抛异常为例外)。

你可以使用以下函数 −

  • _.find:在找到元素后就会跳出循环。例如,

_.find([1, 2, 3, 4], (element) => {
   // Check your condition here
   if (element === 2) {
      return true;
   }
   // Do what you want with the elements here
   // ...
});
  • 从each中抛出异常。例如,

try {
   _([1, 2, 3, 4]).each((element) => {
      // Check your condition here
      if (element === 2) {
         throw new Error();
      }
      // Do what you want with the elements here
      // ...
   })
}
catch (e) {
   // Do nothing.
}

更新于: 2019年12月2日

268次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.