-1
"incident"가 발견 될 때마다 함수 내에서 iterated되는 nrOfFoundIncidents을 전역 변수로 선언합니다. 그러나 함수가 실행 된 후에 변수가 함수 외부에서 선언 되더라도 변수는 다시 비어 있습니다.전역 변수가 반복되지 않음
왜 그런가요? 어떻게해야합니까?
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
편집 : 나는 관련 정보를 생략 할 수 있기 때문에 위험의 코드의 나머지 부분과 기능을 업데이트.
일치하는 항목이 있습니까? 당신은 그것이 증가되고 있는지 확신합니까? –
요청한 정보로 내 질문을 업데이트했습니다. – holyredbeard
@LeeMeador : 예, 200 %는 기능이 실행되는 동안 (1, 2, 3 등 ...) 확인하기 때문에 확실합니다. – holyredbeard