This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I am trying to break from a foreach loop. I want to test conditions and break from the loop once the condition is met. The problem is it keeps looping through the json array, even on the false ones. I just want it to stop if the condition is met. I am aware that you cannot actually break from a foreach loop but what is a good alternative here? I am having trouble understanding where to put the break statements. Thank you very much.
$.ajax({
// Get the values of the cce json file
url: 'file.json',
success: function (data) {
data.forEach(function(row) {
if (row.ATTR == feature.properties.AATR) {
// code to execute here
// once the condition is met once, stop execution of foreach
} else {
// some other code to execute
// keep going
}
You can't break forEach loop. You need to use a different type of loop.
See the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
You should use a for loop. It is a function that simulate it.
for (var i in data) {
if (condition_to_break) {
break;
}
}
.forEach is a function and doesn't do break.
Related
This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm trying to create "dynamic" cascading dropboxes, and I almost have it done. However, I'm running into an issue dealing with adding a .change() listener onto every variable inside of an array that contains the <select> field ids.
So if I use:
fields[0].change(function() {populateFields(1, 0, xml);});
fields[1].change(function() {populateFields(2, 1, xml);});
The code works perfectly. However, I would prefer to use something like this:
for (i=1; i<numberOfFields; i++){
p = i-1; current = i;
fields[p].change(function() {populateFields(current, p, xml);});
}
So that I can have a variable number of fields, because the current code is limited to three fields. The for loop currently works, but doesn't work after the second field is entered.
Any help would be appreciated.
NOTE: This is not a question about variables or passing variables into functions, but rather adding a event listener to an array. The marked answer was the correct answer.
You can use Array.prototype.forEach(), and in the function that you pass in you can put a guard for the case where you are processing the first element:
fields.forEach(attachChangeHandler);
function attachChangeHandler(field, i) {
if (i === 0) { return; }
field.change(function() {
populateFields(i + 1, i, xml);
});
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I have known the key of closure is about scope. But I don't know the specific execution order of it.
A classical code from 《Professional JavaScript for Web Developers 3rd Edition》about closures.
function createFunctions(){
var result=new Array();
alert('haha');
for(var i=0;i<10;i++){
result[i]=function(){
alert(i);
return i;
};
}
return result;
}
var a=createFunctions();
To my surprise, 'haha' was alerted while none of 'i' were alerted.I was just assigning the function to variable a.Why the statement "alert('haha')" was alerted while the cycle wasn' t executed?
when I add the below code,
var a=createFunctions();
alert(a[2]);
why it alerted like this
function (){
return i;
}
not like
function (){
return 2;
}
Furthermore when I add the below code, what will being the order of statements executed especially the statements in the cycle.
var a=createFunctions();
alert(a[2]());
When you call
var a=createFunctions()
alert('haha') is executed immediately, and an array of 10 functions is created and assigned to the variable 'a', each function alerting 'i' and returning it.
However, by the time any of those functions is called (provided you call them after creating them) the value of i is '10' (the loop termination value). So every time you call one of the functions, with
alert(a[x]())
( with any value of x = 0 thru 9 )
it will alert(10) as the function executes and alert(10) again when it returns.
Why the statement "alert('haha')" was alerted
Because it was an alert statement in the function you called.
while the cycle wasn' t executed
The cycle was executed. The cycle just creates some functions and assigns them to positions in an array. You never call any of those functions.
and when I add the below code, what will being the order of statements executed
It depends where you add it.
This question already has answers here:
Are all javascript callbacks asynchronous? If not, how do I know which are?
(5 answers)
Closed 7 years ago.
I am a little confusing about the async function and sync function, how can I determine if it is an async function?
My assumption is all the function which accept a callback is non-block and async, but here is a exception I found:
I found the Array.prototype.forEach is a block function even if it accept a callback as a parameter.
function test(){
[1,2,3,4,5].forEach(function(item){
for(var i =0; i<100000; i++){
console.log('test');
}
});
console.log('end');
}
test();
this function will continue to print test until all the callback finish, it won't return at once to run console.log('end')
really confusing, how can I determine if a function will return at once?
You can use the common sense rule here, is there any need for async in your code? Why do we need to delay the function? All of the array items are available for you, even if they were not, there should be another reader for example which is async then populate the array with avaialble items and then iterate over them. If you need async you will notice this for sure.
This question already has answers here:
Unknown JavaScript syntax before for...in
(3 answers)
Closed 7 years ago.
While reading code from some project, I stumbled on this KEYVAL:
KEYVAL:
for(key_name in arg_map) { // iterates over hash key|value pairs
// if this key_name belongs to this object, not proto
if(arg_map.hasOwnProperty(key_name)) {
// skip dependent keys during iteration
if(key_name.indexOf('_') === 0) { continue KEYVAL; }
// update independent key value
anchor_map_revise[key_name] = arg_map[key_name];
// update matching dependent key
key_name_dep = '_' + key_name;
if(arg_map[key_name_dep]) {
anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
} else {
delete anchor_map_revise[key_name_dep];
delete anchor_map_revise['_s' + key_name_dep];
}
} // if end
} // for end
What is that? What the purpose of this? Is it part of JS syntax?
It is a label. A label is an identifier (here: KEYVAL), followed by a colon (:), that precedes a statement (in this case, for).
A continue or break statement can use a label (in your case continue KEYVAL) to specify which loop to continue with, or break from. In this case, the KEYVAL: for is the innermost loop, so the label is actually not necessary; but labels are useful if you need to break from several levels at once.
See more on MDN.
EDIT: for, not while.