要for
在JavaScript中尽早停止循环,请使用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
}
}
如果您处于ES2015(aka ES6)环境中,则对于此特定用例,可以使用Array#findIndex
(查找条目的索引)或Array#find
(查找条目本身),两者均可进行填充/填充:
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#findIndex
在回调第一次返回真值时停止,将该调用的索引返回给回调;它返回-1
如果回调从不返回truthy值。Array#find
当它找到您要查找的内容时也会停止,但是它返回条目,而不是它的索引(或者undefined
如果回调函数从不返回真实值)。
如果使用的是与ES5兼容的环境(或ES5填充程序),则可以在数组上使用新some
函数,该函数将调用回调,直到回调返回真实值:
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`
}
});
如果您使用的是jQuery,则可以使用jQuery.each
循环遍历数组。看起来像这样:
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
}
});