我有这个字符串:
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类.
>日期(年/月/日)
>数量
>性格
因此: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"])
现在我该如何做同样的事情,但用特定的字符检索特定日期或月份的总和.
这是我目前的小提琴:http://jsfiddle.net/javascript/pBNNt/8/
像:结果[“09/2012,ABC”]
解决方法
那个怎么样:
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);