javascript - Court-circuit Array. for On dirait une pause.

Mots clés : javascriptarraysforeachjavascript

meilleur 4 Réponses javascript - Court-circuit Array. for On dirait une pause.

vote vote

96

var BreakException = {};    try {    [1, 2, 3].forEach(function(el) {      console.log(el);      if (el === 2) throw BreakException;    });  } catch (e) {    if (e !== BreakException) throw e;  }
[1, 2, 3].some(function(el) {    console.log(el);    return el === 2;  });
vote vote

80

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];  for (let el of arr) {    console.log(el);    if (el === 5) {      break;    }  }
for (const [index, el] of arr.entries()) {   if ( index === 5 ) break; } 
vote vote

72

[1,2,3].every(function(el) {     return !(el === 1); }); 
[1,2,3].every( el => el !== 1 ) 
if (!Array.prototype.every) {   Array.prototype.every = function(fun /*, thisp*/)   {     var len = this.length;     if (typeof fun != "function")       throw new TypeError();      var thisp = arguments[1];     for (var i = 0; i < len; i++)     {       if (i in this &&           !fun.call(thisp, this[i], i, this))         return false;     }      return true;   }; } 
vote vote

70

var array = [1, 2, 3]; for (var i = 0; i < array.length; i++) {   if (array[i] === 1){     break;   } } 

Questions similaires