-1

我声明了一个全局变量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

编辑:我用其余代码更新了函数,因为存在遗漏相关信息的风险。

4

1 回答 1

1

您的代码实际上完全按照您的预期工作。请参阅this fiddle以获取证据。

http://jsfiddle.net/vxbRV/

它记录:

found a match 1
found a match 2
found a match 3
after code runs: 3 

这证明变量正在按照您的预期递增。

无论您遇到什么问题,都不是此发布代码的直接部分。

于 2013-01-18T00:25:47.950 回答