Posted By

Waltem on 10/10/15


Tagged

array foreach some every


Versions (?)

forEach. How to break?


 / Published in: JavaScript
 

Array.prototype.forEach You can't break forEach. So use "some" or "every". Array.prototype.some some is pretty much the same as forEach but it break when the callback returns true. Array.prototype.every every is almost identical to some except it's expecting false to break the loop.

  1. var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
  2.  
  3. ary.some(function (value, index, _ary) {
  4. console.log(index + ": " + value);
  5. return value === "CoffeeScript";
  6. });
  7. // output:
  8. // 0: JavaScript
  9. // 1: Java
  10. // 2: CoffeeScript
  11.  
  12. ary.every(function(value, index, _ary) {
  13. console.log(index + ": " + value);
  14. return value.indexOf("Script") > -1;
  15. });
  16. // output:
  17. // 0: JavaScript
  18. // 1: Java

Report this snippet  

You need to login to post a comment.