var a = prompt("Login: ");
if (a == "GeoGame") {
alert("press Ok");
} else {
alert("Wrong Login");
break;
}
var c = prompt("Password");
if (c == "2564GGT456") {
alert("George Gamer Login: GeoGame Bank: 200,567.56$ Нажмите OK что бы снять деньги.");
alert("Деньги уcпешно перечислены на ваш аккаунт");
} else {
alert("Wrong Password");
}
задан 3 янв 2017 в 15:01
1
Вот так должно работать
(function () {
var a = prompt("Login: ");
if (a == "GeoGame") {
alert("press Ok");
} else {
alert("Wrong Login");
return;
}
var c = prompt("Password");
if (c == "2564GGT456") {
alert("George Gamer Login: GeoGame Bank: 200,567.56$ Нажмите OK что бы снять деньги.");
alert("Деньги уcпешно перечислены на ваш аккаунт");
} else {
alert("Wrong Password");
}
})();
ответ дан 3 янв 2017 в 15:09
Mikhail VaysmanMikhail Vaysman
14.2k1 золотой знак20 серебряных знаков31 бронзовый знак
А какой break
в операторе if
? break
можно вставлять либо внутри цикла, либо в операторе switch
.
Можете вынести весь код в функцию и вместо break
использовать return
ответ дан 3 янв 2017 в 15:07
Anton ShchyrovAnton Shchyrov
32.9k2 золотых знака29 серебряных знаков59 бронзовых знаков
0
можете использовать return false заместо break;
ответ дан 3 янв 2017 в 15:10
L. VadimL. Vadim
3,4061 золотой знак9 серебряных знаков18 бронзовых знаков
Можно и без промисов, на обычных колбеках:
function asyncLoop(fn, i, end) {
if (i < end) fn(i, () => asyncLoop(fn, i + 1, end));
}
function worker(i, next) {
client.hgetall('space' + i, (err, obj) => {
if (err) return; // break
next();
});
}
asyncLoop(worker, 0, 9);
На промисах примерно так:
let p = Promise.resolve();
for (let i = 0; i < 9; i++) {
p = p.then(() => new Promise((resolve, reject) => {
client.hgetall('space' + i, (err, obj) => {
if (err) reject(err); // break
else resolve();
});
}));
}
p.catch(err => console.error(err));
You can’t break from the each
method—it emulates the native forEach
method’s behavior, and the native forEach
doesn’t provide to break the loop other than throwing an exception.
See the quote from mozilla doc:
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Early termination may be accomplished with:
A simple loop
A for…of loop
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.
But there is a solution of it which isArray.every
method, which uses it’s callback’s return value to iterate over next element.
every
executes the providedcallback
function once for each element present in the array until it finds one wherecallback
returns a false value. If such an element is found, theevery
method immediately returns false.
Example of Array.every
method:
var orgs = ['NSO', 'CRY India', 'WHO', 'ImageResizingOrg', 'Unicef'];
var returnval = true;
orgs.every(function (text) {
if (text.includes('ImageResizingOrg')) {
//you can do anything here like firing click event as you have done in your code
returnval = false;
}
console.log(text);
return returnval;
});
In this post we cover everything you need to know about how to break a JavaScript forEach loop, the alternatives, errors, the best course of action and more.
In this post we will be covering how to break a JavaScript forEach loop with as little technical jargon as possible so you will have everything you need right here without having to look any further!
It is not possible to break a JavaScript forEach loop in the conventional sense, so what should you do instead?
In this post, we will cover everything you need to know about how to break a JavaScript forEach loop as well as the alternatives.
Let’s get started!
How to break a JavaScript foreach loop
If you need to to stop or perform a break in a JavaScript forEach loop then you probably shouldn’t be using a forEach loop, instead try using either a for loop, or Array.prototype.some which we will look at in more detail later in the post.
Array.prototype.forEach is designed to loop over every item in an array once whilst providing you with the array item, the index and the full array in a callback that you provide.
Because of this there is no way to just break out of it.
If you have tried to use a break statement within a forEach loop then you would have got the error “Uncaught SyntaxError: Illegal break statement”, which is expected because you can only use the break statement inside the direct scope of a loop, and not a function (even if the function is inside of the loop).
Here is an example of the error:
[1, 2, 3].forEach(a => {
console.log(a)
break
})
// Uncaught SyntaxError: Illegal break statement
With all that said, we do have a few options for how to replicate a break in a JavaScript forEach loop if you still need to find a way to break a forEach loop.
How to break a JavaScript foreach loop using an exception
One option is to throw an exception with the callback you pass into the Array.prototype.forEach function.
By doing this you will cause an error which will stop all processes in your JavaScript application.
Because you don’t want your whole application to stop, we will need to wrap the Array.prototype.forEach loop in a try catch statement so we can catch the error that we are going to throw so that the error will act as a break statement.
Before we get into the example, this is really not ideal and as I have said at the start if you need to break out of a loop then your best option is to not use forEach and instead use a for loop to break, or the Array.prototype.some method.
Here is the example of how to use throwing an error to break a JavaScript foreach loop:
const breakFE = () => {
throw new Error("BREAK_FE")
}
const handleBreakFEError = e => {
if (e.message !== "BREAK_FE") {
throw e
} else {
console.log("javascript foreach break!")
}
}
try {
[1, 2, 3].forEach(item => {
if (item > 1) {
breakFE()
}
console.log(item)
})
} catch (e) {
handleBreakFEError(e)
}
// 1
// javascript foreach break!
You could take this one step further and create a helper function, or even modify the Array object itself, but in general you should not do this and there is very little reason to do it.
Here is how that could look though:
Array.prototype.forEachWithBreak = function(callback) {
const breakFE = () => {
throw new Error("BREAK_FE")
}
const handleBreakFEError = e => {
if (e.message !== "BREAK_FE") {
throw e
} else {
console.log("javascript foreach break!")
}
}
try {
this.forEach((...args) => callback(...args, breakFE))
} catch (e) {
handleBreakFEError(e)
}
}
[1, 2, 3].forEachWithBreak((item, index, arr, breakFE) => {
console.log(item, index)
breakFE()
})
// 1 0
// javascript foreach break!
How to break a JavaScript foreach loop using an if statement and return
You can’t actually “break” a JavaScript forEach loop using an if statement because it will still perform all of the iterations on your array.
But you can drastically lower the amount of work that happens on each iteration.
If you are doing a large amount of computations on each iteration of your forEach loop then, whilst not perfect, you could use an if statement to mitigate doing that work which would be a little bit like calling continue on each iteration.
Here is an example of how you can use an if statement to skip computations in the forEach loop:
let breakFe = false;
[1, 2, 3].forEach(item => {
if (item > 1) {
return
}
console.log(item)
})
As you can see this works by just returning at the start of each iteration to keep the computational work as minimalist as possible by preventing any more code being run in your callback.
This is far from ideal, and it would be better to use a method that can enable you to break out or to use a for loop.
Alternatives to a JavaScript forEach break
There are a few options we can use for alternatives for the foreach loop in JavaScript, and they are the best solutions if you need to break out of a forEach loop.
Using a for loop as an alternative to a forEach loop to break
The first one, and the one I personally would recommend in this situation, would be to go with a standard for loop and break statement.
I have a full post on how you can break out of a for loop here.
Here is an example of how you can use a for loop to break a loop:
const myArray = [1, 2, 3];
for (let i = 0; i < myArray.length; i += 1) {
const arrayItem = myArray[i]
if (arrayItem > 1) {
break
}
console.log(arrayItem, i, myArray)
}
As you can see in the above example, with very little work we can get the for loop to do exactly what the forEach loop does for us except from now we can use the break statement to break out of additional iterations.
Using a while loop as an alternative to a forEach loop to break
A while loop is essentially the same principle as the for loop except that you don’t define the index in the while loop scope.
Here is an example of how you can use the while loop as an alternative to the forEach loop to break with:
const myArray = [1, 2, 3];
let index = 0;
while (index < myArray.length) {
const arrayItem = myArray[index]
if (arrayItem > 1) {
break
}
console.log(arrayItem, index, myArray)
index += 1
}
Using a Array.prototype.some as an alternative to a forEach loop to break
The last alternative that you can use for a forEach loop in order to perform a kind of break is the Array.prototype.some method.
You still won’t be able to call the break statement from within it, but instead you are able to return a boolean from your callback which the some loop will use as an indicator to stop iterating over array items.
The original purpose of the Array.prototype.some method is to know if an item exists within an array, if it does the method will return true, if not then it will return false.
We can make use of this to create a break-like functionality by returning true in our callback when we want to emulate a break statement.
Here is an example of how to use the some method to break a loop:
[1, 2, 3].some(a => {
console.log(a)
return true
})
// 1
// true
Summary
To summarize this post in a few words, if you need to break out of a JavaScript Array.prototype.forEach then you should not be using a JavaScript Array.prototype.forEach and instead you should be using either a for loop or the Array.prototype.some method.
There we have how to break a JavaScript foreach loop, if you want more like this be sure to check out some of my other posts!
I hope this post has helped, but before you go, make sure you try my fun interactive quiz to see if you are a novice, intermediate, or expert React engineer.
It will only take about 1 — 3 minutes, so you have nothing to lose, test your abilities now.
Take Quiz.
Are you a novice, intermediate or expert react engineer?
Find out here by taking my fun, interactive, quick quiz which takes approximately 1 — 3 minutes. How well will you will do?
Some graphics used on this post were made using icons from flaticon.
The array forEach()
method is commonly used among TypeScript and JavaScript developers. However, developers often come across unexpected behaviors trying to exit or break the forEach()
method using the break
keyword to prevent executing any additional logic to subsequent elements of an array.
For instance, if we try to run the following example:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
myArray.forEach((value) => {
if (value > maxValue) break;
console.log('Current value is ', value);
});
Unfortunately, this will cause errors in your code.
If you are using TypeScript, it will throw the following error: Jump target cannot cross function boundary.(1107)
If you are using JavaScript, it will throw the following error: Uncaught SyntaxError: Illegal break statement
Fortunately, there are different ways to fix this issue.
Throw an error to break the loop
To fix this error and successfully break the forEach()
loop either in TypeScript or JavaScript, wrap the forEach()
logic inside a try/catch
statement and throw an error inside the forEach()
callback function to break the loop.
Throwing an error forces the program to immediately stop running any additional logic. Hence, “breaking” the loop.
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
try {
myArray.forEach((value) => {
if (value > maxValue) throw new Error("Max limit reached");
console.log('Current value is ', value);
});
} catch(error) {
console.error("error ", error);
}
While this solution works, it opens the room to let the code keep running in case there is an unexpected error different from our custom Error("Max limit reached")
error.
To make sure we keep running the code as long as we trigger are custom error, verify the error
contains the message
property. Also, verify the error.message
value matches the custom message. This can look like the following example:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
const errorMaxLimit = "Max limit reached";
try {
myArray.forEach((value) => {
if (value > maxValue) throw new Error(errorMaxLimit);
console.log('Current value is ', value);
});
} catch(error) {
if (!error.property || error.property !== errorMaxLimit) {
// another error has happened
throw error;
}
}
Use return
to prevent running undesired logic (alternative solution)
Another solution is to use the return
keyword instead of the break
keyword to prevent running undesired logic.
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
myArray.forEach((value) => {
if (value > maxValue) return; // use the "return" keyword instead of the "break" keyword
console.log('Current value is ', value);
});
For instance, the previous snippet of code will no longer log “Current value is ” for each of the elements of the array myArray
. While using the return
keyword will prevent running undesired logic, this solution can suffer from performance issues.
Why using return
inside the forEach()
loop causes performance issues?
If you think about it, using the return
keyword doesn’t actually “break” the forEach()
loop. It only prevents running undesired logic.
Hence, if myArray
array has, .i.e., 100000 elements, the callback function will execute for each of the array elements even if it only logs “Current value is ” for the first four elements.
Therefore, we are still running unnecessary logic in the background.
Why do you recommend using return
if it can have performance issues?
It all comes down to how having an idea of the average number of elements in your array.
For instance, if I know my array will typically have a few more elements than the limit established prior to deciding to programmatically break the loop, I would rather use the return
keyword than throwing an error and wrapping the forEach()
loop in a try/catch
statement.
In other words, it is cleaner and I consider “ok” to compromise performance and executing a few additional callback executions for the sake of preventing adding custom logic to break the forEach()
loop.
Any time more logic is added to the code it means additional testing needs to be done upon the new logic.
On the other hand, if the loop might have a big gap between the limit established to break the loop and the number of elements the array could actually have, I would not use the return
keyword as my first solution.
Use a traditional for
loop or a for of
loop and preserve the break
keyword
Another solution is to not use the forEach()
loop and use a traditional for
loop. In that way, there wouldn’t be the need to throw an error as the break
keyword would effectively break the loop.
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
for (let i = 0; i < myArray.length; i++) {
const value = myArray[i];
if (value > maxValue) break;
console.log('Current value is ', value);
}
This solution also applies when using a for of
loop.
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const maxValue = 4;
for (let value of myArray) {
const value = myArray[i];
if (value > maxValue) break;
console.log('Current value is ', value);
}
While this might not be necessarily a solution to breaking the forEach()
loop, using the for
or for of
loop along with the break
keyword would be a much simpler approach to solving the main issue which is to break the loop.
Conclusion
It is easy to fool yourself by thinking the break
keyword will break the loop when using the forEach()
method. Luckily, there are different alternatives available to break the loop or prevent from running undesired logic by making little tweaks to our code.
Did this article solve your problem?
Hopefully, this article provides you with different solutions you can apply to a common error that most likely any TypeScript/JavaScript developer has experienced at least once in their career.
Share your thoughts by replying on Twitter of Become A Better Programmer or to my personal Twitter account.
This is one of the many things I keep forgetting every now and then. Other things like taking out clothes from the washing machine, watering my plants, okay but this post is not about me being forgetful. I am sure lot many of you reading this post do know this but still its not until you try to break out of the «forEach» loop that you realize you made the same mistake once again. This post is just a reminder for most of us and maybe a short clarification for the rest of us.
Moving ahead with an example because examples are the quickest way to explain stuff. Lets say we have an array of flowers and we want to collect all the flowers unto my favorite «Tulip» starting from the first one. Yes, please dont make it complicated by throwing in scenarios like what if there are multiple «Tulips«. We have an array of flowers, where each flower appears once like so:
How would you do it? If I were you I’d rush to get the «forEach» loop down first but not this time. Lets use the conventional for loop and get this done first. Silly but helpful. Easy said, easy done! Then we shall also try that out with my favorite «forEach» loop. Take a look at the following snippets.
Had you tried that on your own, you’d have come across this error that says «Illegal break statement«. You can’t break out of the forEach loop after you’re done collecting «Tulip«. You may have already figured out but don’t worry if you haven’t and let me tell you how does the forEach loop differ from all the conventional loops. «forEach» more than being a loop, is a function call and you know it right from the syntax. This function takes another callback function and mind it, the callback function has to be a synchronous function. The synchronous callback function essentially is then called in interation on the array on which you did call the «forEach» loop. I understand, that this may not sound very intuitive. So, let me try explaining this with a demo polyfill of the «forEach» function. You can easily make it go crazy throwing errors but for a quick example, it should suffice. For complete implementation you can see this.
Now when you look at the poyfill (customForEach), you’ll be able to comprehend the situation much clear. You’d also agree how placing a «break» statement inside a function (named callback) is inappropriate. Read what MDN docs say. Even if you assumed that something like a «break» statement was valid inside a function (which indeed isn’t the case), you’d see that it would not be able to break out of the loop, since there’s no way you can add a «break» statement inside the internal loop. Why? because you simply cannot access it from outside.
Accomplishing the task we took as an example here for this post, is not a tough job. There are numerous ways this can be done but apart from this example, for your use-case checkout the alternatives available at your disposal. Again, this is not an exhasutive list but then the purpose of this post is served and anything beyond this would only stretch the content unnecessarily I believe. Also since I have now written this post, I think I won’t repeat this mistake or will I?
Originally Posted Here —
https://mayankav.webflow.io/blog/you-cant-break-the-foreach-loop
2 ответа
break состоит в том, чтобы вырваться из цикла, например, в то время как, switch и т.д., которого у вас здесь нет, вам нужно использовать return
для разбить поток выполнения текущей функции и вернуться к вызывающему абоненту.
function loop() {
if (isPlaying) {
jet1.draw();
drawAllEnemies();
requestAnimFrame(loop);
if (game == 1) {
return
}
}
}
Примечание. Это не охватывает логику условия if или когда возвращаться от метода, для этого нам нужно иметь больше контекста относительно методов drawAllEnemies
и requestAnimFrame
, а также как значение game
обновлено
Arun P Johny
21 март 2014, в 02:40
Поделиться
Вам нужно убедиться, что requestAnimFrame перестает быть вызванным после игры == 1. Инструкция break только выходит из традиционного цикла (например, while()
).
function loop() {
if (isPlaying) {
jet1.draw();
drawAllEnemies();
if (game != 1) {
requestAnimFrame(loop);
}
}
}
Или, альтернативно, вы можете просто пропустить второе условие if
и изменить первое условие на if (isPlaying && game !== 1)
. Вам нужно будет сделать переменную, называемую игрой, и дать ей значение 0. Добавьте 1 к ней в каждую игру.
Bart
21 март 2014, в 03:43
Поделиться
Ещё вопросы
- 1Сортировка предметов в выпадающем списке
- 0Использование баров из Google-графиков в качестве кнопок
- 1Выражение. Вызовите группу, затем выберите?
- 0ASN1C компиляция
- 1получить размер InputStream в Java
- 0Использование get_class в блоке try — catch
- 1Мой предварительный просмотр камеры растянут и сжат. Как я могу решить эту проблему?
- 0Почему мой код выводит только часть входной строки?
- 0Динамическое внедрение службы в angular.js
- 0Установка MAMP на компьютер с установленным MySql и настройкой PHP на localhost?
- 0Как установить Qwidget внутри QGraphicsWidget?
- 0Вызов метода контроллера из CUserIdentity
- 1Счетчик значений по группе не показывает счетчик значений NULL / NA в пандах
- 1Новое приложение для замораживания ниток
- 1Есть ли какой-то конкретный способ заставить систему удалить всплывающее окно появляется слушатель в Android
- 0Я пытаюсь заполнить поле со списком в front-end значением поля из базы данных
- 0Как получить идентификатор из списка объектов, используя AngularJS?
- 1Node.js — console.log не показывает элементы в массиве, а вместо этого показывает [Object]
- 0Инициализировать не копируемый сторонний базовый класс с указателем на объект
- 0JQuery Datepicker: как отрицать это, используя мой CSS
- 0Как проверить поле ввода с помощью php
- 0Ошибки PEAR в отдельном всплывающем окне
- 0сравнить два входных значения в проверке входных данных HTML JavaScript?
- 0изменить первое и последнее значение строки PHP
- 1Система оценки фигуристов
- 0Как я могу разработать мобильное веб-приложение с использованием Visual Studio 2012 и jquery с asp.net MVC
- 1Как вызвать Interstitial, нажав на элемент в списке, который проходит через адаптер?
- 1Слияние и добавление данных с помощью Python Pandas [duplicate]
- 1Неожиданное поведение в константном назначении ES6
- 1составление данных формы с помощью HttpClient
- 0при нажатии ссылки отображается строка с первым символом в диапазоне от 0 до 9
- 1Xming: почему JFrame потерял фокус, когда установлен Undecorated (true)?
- 0Сравнить символ в строке (который изменяется оператором «=»)
- 0Как ждать дочерней директивы рендера?
- 0Поменяйте местами два HTML-тега, между которыми есть некоторые фиксированные теги
- 0AngularJS — директива не загружена
- 0<a href не срабатывает после вызова функции jquery в IE. Прекрасно работает с Chrome и FF
- 1Приложение отлично работает на эмуляторах, но вылетает на устройстве с: java.lang.UnsatisfiedLinkError: сбой dlopen: не удается найти символ «__aeabi_memcpy»
- 0Как обновить набор указателей с ++?
- 0Подсчитать количество промежутков до пролета с определенным идентификатором
- 0Отображение / скрытие div в зависимости от значения Select
- 1как быстрее шифровать файлы
- 0Обязательно ли использовать кладку на контейнере div?
- 1Генерирование Java-классов из базы данных с помощью hibernate и maven — AnnotationConfiguration отсутствует?
- 1Получить значение даты и времени из таблицы SQL Server с помощью C # Sql Reader
- 1Google Map запрашивает местоположение в порядке, но не центрирует карту
- 0Извлечение Src и вставить перед HTML-ссылку с помощью JQuery
- 0Загрузка файла $ _FILES массив пуст
- 1KnockoutJS — настройка меню выбора на основе выбора в другом меню
- 0Область применения в функциях ссылок