arrays - Can forEach in JavaScript make a return? -


i wonder if foreach in javascript can make return, here code:

var = [0, 1, 2, 3, 4];  function fn(array) {   array.foreach(function(item) {     if (item === 2) return false;   });    return true; }  var ans = fn(a); console.log(ans); // true 

i want find out if 2 in array, if so, return false, seems foreach function has looped whole array , ignore return.

i wonder if can answer want foreach ( know can want using for(..))? dear friend, pls me, great thanks!

you can use indexof instead https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/indexof

function fn(array) {   return (array.indexof(2) === -1); } 

also documentation foreach - https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/foreach

note: there no way stop or break foreach() loop other throwing exception. if need such behaviour, .foreach() method wrong tool, use plain loop instead.

so, return value cannot used way using it. throw (which not recommended unless need error raised there)

function fn(array) {   try {       array.foreach(function(item) {          if (item === 2) throw "2 found";       });   }   catch (e) {     return false;   }    return true; } 

Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -