5

我有这个字符串:

var result = " / 07-09-2012 73 ABC / 11-09-2012 195 DEF/ 03-09-2012 95 / 04-09-2012 188 ABC / 31-10-2012 72 / 18-09-2012 205 / 26-09-2012 244 ABC / 14-09-2012 86 / 20-09-2012 92 DEF / 28-09-2012 97 / 01-09-2012 95 DEF/ 17-09-2012 95 / 17-09-2012 83 / 12-09-2012 95 / 18-09-2012 95 ABC / 18-09-2012 69 / 21-09-2012 95 / 21-09-2012 95 ABC/ 24-09-2012 144 / 28-09-2012 93 DEF";

字符串分为 3 类。

  1. 日期(日/月/年)
  2. 数字
  3. 特点

因此:07-09-2012 73 ABC

我想得到数字的总和,其中日期为 09 并且具有字符 ABC。

目前,从另一个问题中,我发现了如何在字符串没有字符时仅检索日期示例:http: //jsfiddle.net/javascript/pBNNt/10/

var result = " / 07-09-2012 73 / 11-09-2012 195 / 03-09-2012 95 / 04-09-2012 188 / 31-10-2012 72 / 18-09-2012 205 / 26-09-2012 244 / 14-09-2012 86 / 20-09-2012 92 / 28-09-2012 97 / 01-09-2012 95 / 17-09-2012 95 / 17-09-2012 83 / 12-09-2012 95 / 18-09-2012 95 / 18-09-2012 69 / 21-09-2012 95 / 21-09-2012 95 / 24-09-2012 144 / 28-09-2012 93";

var resultArr = result.split('/');
var results = {}; //sum by month
for (var i = 0; i < resultArr.length; i++) {    
    if ( resultArr[i].length >= 11) { //it has date
        var resultTkn = resultArr[i].split(' ');

        if (resultTkn[1].length == 10) { //it is a date
            var date = resultTkn[1].split('-');
            var sum = 0;
            if (results.hasOwnProperty(date[1])) {
                sum = results[date[1]];
            }

            sum += parseFloat(resultTkn[2]);
            results[date[1]] = sum;
        }
    }
}
$('div').text(results["09"])

​</p>

现在我该如何做同样的事情,但要检索具有特定字符的特定日期或月份的总和。

这是我目前对字符串的小提琴:http: //jsfiddle.net/javascript/pBNNt/8/

就像是:results["09/2012,ABC"]

4

1 回答 1

3

那个怎么样:

function search(result, cat) {
    var data = [],
        lines = result.split(/\s*\/\s*/);
    for (var i = 0; i < lines.length; i++) {
        if (lines[i] === "") continue;
        var s = lines[i].split(/\s+/);
        data.push({
            date: s[0],
            number: parseInt(s[1], 10) || 0,
            char: s[2] || ""
        });
    }

    var num = 0;
    for (var j = 0; j < data.length; j++) {
        if ((cat.char && data[j].char === cat.char) &&
            (cat.date && data[j].date.indexOf(cat.date) !== -1)) {
            num += data[j].number;
        }
    }
    return num;
}

var result = " / 07-09-2012 73 ABC / 11-09-2012 195 DEF/ 03-09-2012 95 / 04-09-2012 188 ABC / 31-10-2012 72 / 18-09-2012 205 / 26-09-2012 244 ABC / 14-09-2012 86 / 20-09-2012 92 DEF / 28-09-2012 97 / 01-09-2012 95 DEF/ 17-09-2012 95 / 17-09-2012 83 / 12-09-2012 95 / 18-09-2012 95 ABC / 18-09-2012 69 / 21-09-2012 95 / 21-09-2012 95 ABC/ 24-09-2012 144 / 28-09-2012 93 DEF";

var total = search(result, {
    char: "ABC",
    date: "-09-2012"
});

console.log(total);

演示:http: //jsfiddle.net/pBNNt/12/

于 2012-11-22T13:27:19.423 回答