-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

コードは実際には期待どおりに機能します。証拠としてこのフィドルを参照してください。

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 に答える