Para interromper um forloop no início do JavaScript, use break:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
Se você estiver em um ambiente ES2015 (também conhecido como ES6), para este caso de uso específico , poderá usar Array#findIndex(para encontrar o índice da entrada) ou Array#find(para encontrar a própria entrada), os quais podem ser shimmed / polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndexpara na primeira vez em que o retorno de chamada retorna um valor verdadeiro, retornando o índice dessa chamada para o retorno de chamada; retorna -1se o retorno de chamada nunca retornar um valor verdadeiro. Array#findtambém para quando encontra o que você está procurando, mas retorna a entrada, não o índice (ou undefinedse o retorno de chamada nunca retornar um valor verdadeiro).
Se você estiver usando um ambiente compatível com ES5 (ou um shim ES5), poderá usar a nova somefunção em matrizes, que chama um retorno de chamada até que o retorno retorne um valor verdadeiro:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
Se você estiver usando jQuery, poderá usar um jQuery.eachloop através de uma matriz; que ficaria assim:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});