如何在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.