How to break from objx(data).each(function(item) iteration? - javascript

How to break from objx(data).each(function(item) iteration when a certain condition is met.
My Json string is below:
var data= [{"field1": "0","field2": "2"},{"field1": "7","field2": "2"},{"field1": "1","field2": "5"}];
Here is a my code:
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//doing some job;
return;
}
alert("after if is executed");// this alert coming inspite of giving
}); // return in if block
}
i think the return is only enabling it to come out of function but not from the loop. i dont want this unnecessary iteration once my condition is met and job is done.
can anyone suggest how to come out of this each loop?

return false;
Returning false breaks out of the each function.

To exit the jquery each loop
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//to stop the loop here
return false; // here - will exit the each loop
}
});
}

Related

jQuery function doesn't exit after return [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

Javascript trouble understanding IF loop to use in a script

I'm new at javascript and am using tampermonkey for a website.
What i want to do is monitor a variable on a page and when said variable reaches a certain value, go to another page, do something, and then recheck the value of this variable.
My logic was to:
setInterval(function(){reloadPage1},10000);
var variable = someTextonThisPage;
if(someTextonthisPage meets condition)
{
go to Page2;
execute something on page 2;
setNewValueForVariable; //(or just go back to initial
//and get the new value from there)
}
Now my problem is when the if executes, it goes to page2 keeps looping the if call even if i set the variable to something false.
I tried doing something like:
function doThis()
{
if(condition)
return true;
else return false;
}
if(doThis())
{
goToPage2;
do stuff;
doThis();
}
I end up having the if statement go on and on, going to page 2 and my settimeouts to do something on that page never execute because of the next iteration of the 'if'.
What am i doing horribly wrong in my thought pattern?
Your doThis() function is right. Everything ok with it.
function doThis()
{
if(condition)
return true;
else
return false;
}
But when you check the loop you have to call it one time only. After doing stuff you are again calling doThis() function it is wrong.
if(doThis())
{
goToPage2;
do stuff;
//doThis();
}
And also it depends on how you are calling this loop and functions.
For eg.,
<script>
var i = 0;
onPageLoad()
{
if(i%2==0){
return true;
i++;
}else{
return false;
i++;
}
}
if(onPageLoad()){
goToPage2;
doStuff();
}else{
onPageLoad()
}
</script>
Here when the condition meets the right statement which is i%2 == 0 it will automatically call goToPage2 function otherwise it again going to check the condition.
You can add interval/timeout in the loop to check when the variable is updating and when it calls goToPage2 function.
Hope this helps.

increment not working in controller

$scope.isChecked = function(id){
var i=0,j=0,k=0;
//$scope.abc[i].usertype[j].keywords[0].key_bool=true;
if($scope.abc[i].type_selected == true){
while($scope.abc[i].usertype.length){
while($scope.abc[i].usertype[j].keywords.length){
if($scope.abc[i].usertype[j].keywords[k]._id == id){
if($scope.abc[i].usertype[j].keywords[k].key_bool == true){
$scope.abc[i].usertype[j].keywords[k].key_bool = false;
return false;
}
else{
$scope.abc[i].usertype[j].keywords[k].key_bool = true;
return true;
}
}
k++;
}
j++;
}
}
};
Incrementing k++ is working while incrementing j++ not, can someone explain me this, why such happening?
isChecked function called whenever checkbox is checked/unchecked as:
ng-click="isChecked(l._id)"
Everything works perfectly for 'j=0', but not for later 'j' values.
Simply because of the return statements execution gets out of the function every time a return statement is reached. So j++; is unreachable every time the if statement is executed
for j=0, it goes inside the inner while loop, and when it reaches to the return statement, it comes out of function.
That is why, outer while loop is not getting executed again.
To get more about return, read this
i got the answer.
we have to put k=0; between the 2 while loops.
still thanks guys for ur help

Why is this do-while loop in infinite?

I am learning the do-while loop and am unable to understand why this loop is running infinitely.
var condition = true
var getToDaChoppa = function(){
do {
console.log("I'm the do loop");
} while(condition === true){
console.log("I'm the while loop");
condition = false;
};
};
getToDaChoppa();
You never set the condition variable to false INSIDE the loop, so it will never execute any of your code outside of the loop until this loop has completed (which will never happen given your current example). Make sure that you set the condition variable to false inside the loop:
do {
console.log("I'm the do loop");
if (some_condition_is_met) {
condition = false;
}
} while(condition === true);
Do/While works like this. So you never change the condition inside the loop.
do {
//code block to be executed
}
while (condition);
//Code after do/while
There is a do..while and there is a while..: there is no do..while.. statement.
JavaScript allows block statements independent of other flow-control/definition constructs. Due to lack-of-a-required statement semicolon this does not result in a syntax error (it would in Java).
Here is some additional clarification relating to the syntax; other answers cover the logical error.
do {
console.log("I'm the do loop");
} while(condition === true) // semicolons optional in JS (see ASI):
// 'do..while' statement ENDS HERE
{ // starts a block statement which has naught to do with 'do..while' above
// THERE IS NO WHILE LOOP HERE
console.log("I'm the while loop");
condition = false;
}; // useless semicolon which further leads to confusion
On the other hand, if the do.. was omitted it would have been parsed as "just" a while statement which would have terminated.
// Basic WHILE statement - no 'do..' code, so NOT parsed as a 'do..while'!
while(condition === true)
{ // this block is now part of the 'while' statement loop
console.log("I'm the while loop");
condition = false;
};

Illegal break statement in $.each [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

Categories