I am declaring a global variable, nrOfFoundIncidents that gets iterated inside a function every time an “incident” is found. However, after the function is executed the variable is empty again, even though it’s declared outside the function.
Why is that and what can I do about it?
var INCIDENT_MATCHES = {
trafficAccidents: /(traffic|car) accident|/
robberies: /...
...you get it.
};
// theIncidents[0] = "There was a robbery on the 52th street last nigth...";
// theIncidents[1] = "Two days ago a car crashed into a house...";
// theIncidents[2] = "One person got stabbed outside his home...";
... and so on...
var nrOfFoundIncidents = 0;
function FindIncidents(incidentReports) {
var incidentCounts = {};
var incidentTypes = Object.keys(INCIDENT_MATCHES);
incidentReports.forEach(function(incident) {
incidentTypes.forEach(function(type) {
if(typeof incidentCounts[type] === 'undefined') {
incidentCounts[type] = 0;
}
var matchFound = incident.match(INCIDENT_MATCHES[type]);
if(matchFound){
var matchFound = incident.match(INCIDENT_MATCHES[type]);
nrOfFoundIncidents += 1;
console.log(nrOfFoundIncidents); // 1, 2, 3, 4, 5, 6, 7...
}
});
});
return incidentCounts; // <- returns as it supposed
}
var objectOfIncidents = FindIncidents(theIncidents); <-- as an argument an object containing of categories with reg exp to find them in the text that is searched is provied.
console.log(nrOfFoundIncidents); // <--- 0
EDIT: I updated the function with the rest of the code because of the risk to leave relevant information out.
Your code actually works exactly as you expect it to. See this fiddle for proof.
http://jsfiddle.net/vxbRV/
It logs:
Which proves the variable is being incremented as you expect it to be.
Whatever problem you have is not directly part of this posted code.