Javascript 全局变量不';不要重复

Javascript 全局变量不';不要重复,javascript,function,variables,global-variables,Javascript,Function,Variables,Global Variables,我声明了一个全局变量nrOfFoundIncidents,每次发现“事件”时,它都会在函数中迭代。但是,在函数执行后,变量再次为空,即使它是在函数外部声明的 为什么会这样?我能做些什么 var INCIDENT_MATCHES = { trafficAccidents: /(traffic|car) accident|/ robberies: /... ...you get it. }; // theIncidents[0] = "There was a robbery

我声明了一个全局变量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
var事件匹配={
交通事故:/(交通|汽车)事故|/
抢劫:/。。。
…你明白了。
};
//事件[0]=“昨晚52街发生了一起抢劫案……”;
//事故[1]=“两天前,一辆汽车撞上了一所房子……”;
//事件[2]=“一个人在家门口被刺……”;
... 等等
var nRoffoundEvents=0;
功能查找事件(意外报告){
var incidentCounts={};
var incidentTypes=Object.keys(事件匹配);
incidentReports.forEach(功能(事件){
incidentTypes.forEach(函数(类型){
if(意外事件计数的类型[类型]=“未定义”){
意外计数[类型]=0;
}
var matchFound=incident.match(incident_MATCHES[type]);
如果(找到匹配项){
var matchFound=incident.match(incident_MATCHES[type]);
nRoff+=1;
log(nrOfFoundIncidents);//1,2,3,4,5,6,7。。。
}
});
});

return incidentCounts;//您的代码实际上完全按照您的预期工作。请参阅此提琴以获取证据

它记录:

found a match 1
found a match 2
found a match 3
after code runs: 3 
这证明变量正在按预期的方式递增


您遇到的任何问题都不是此发布代码的直接部分。

有匹配项吗?您确定它会递增吗?我已用您要求的信息更新了我的问题。@LeeMeador:是的,200%确定,因为我在函数运行时检查它(1、2、3等等).@holybeard是
incidentObject
未定义的?这行做什么
函数查找意外事件(theIncidents);
?我不认识它。