我有以下JavaScript语法:
console.log(printClassified(classifyByDayOfWeek(myData)));
mySundaysData = new Array(printClassified(classifyByDayOfWeek(myData)));
console.log(mySundaysData);
var mySundaysTotal = 0;
for(var i=0, len=mySundaysData.length; i<len; i++){
mySundaysTotal += parseFloat(mySundaysData[i][1]);
}
console.log(mySundaysTotal);
Google Chrome控制台:
printClassified(classifyByDayOfWeek(myData)) = [2013-04-21, 1][2013-04-28, 0][2013-05-05, 2][2013-05-12, 0]
mySundaysData = ["[2013-04-21, 1][2013-04-28, 0][2013-05-05, 2][2013-05-12, 0]"]
mySundaysTotal = 2
我想计算数组中的值,对于上面的例子:1 + 0 + 2 + 0它应该给我3,而它给我2就像它可以在console.log(mySundaysTotal)
中看到的那样。即使我有其他阵列mySundaysTotal总是2.为什么?我做错了什么?
编辑: 其余代码:
function sorter(a, b) {
var d1 = new Date(a[0].replace("-", "/")).getDay();
var d2 = new Date(b[0].replace("-", "/")).getDay();
return d1 - d2;
}
function classifyByDayOfWeek(customArr) {
var byDayOfWeek = [[], [], [], [], [], [], []];
for (var i = 0; i < customArr.length; i++) {
var day = new Date(customArr[i][0]).getDay();
byDayOfWeek[day].push(customArr[i]);
};
return byDayOfWeek;
}
function printRaw(arr) {
str = "";
for (var i = 0; i < arr.length; i++) {
str += "[" + arr[i][0] + ", " + arr[i][1] + "]";
}
return str;
}
function printClassified(arr) {
str = "";
str += printRaw(arr[0]);
return str;
}
JSFiddle - http://jsfiddle.net/DanielaVaduva/NUHFu/
答案 0 :(得分:1)
好的,我想我的答案很精致。解析可以做一些工作,但是:
var raw = "\"['2013-04-15', 26]\", \"['2013-04-16', 10]\", \"['2013-04-17', 51]\", \"['2013-04-18', 46]\", \"['2013-04-19', 32]\", \"['2013-04-20', 50]\", \"['2013-04-21', 26]\", \"['2013-04-22', 31]\", \"['2013-04-23', 48]\", \"['2013-04-24', 821]\", \"['2013-04-25', 917]\", \"['2013-04-26', 949]\", \"['2013-04-27', 405]\", \"['2013-04-28', 593]\", \"['2013-04-29', 925]\", \"['2013-04-30', 877]\", \"['2013-05-01', 277]\", \"['2013-05-02', 112]\", \"['2013-05-03', 115]\", \"['2013-05-04', 62]\", \"['2013-05-05', 74]\", \"['2013-05-06', 76]\", \"['2013-05-07', 51]\", \"['2013-05-08', 93]\", \"['2013-05-09', 231]\", \"['2013-05-10', 350]\", \"['2013-05-11', 258]\", \"['2013-05-12', 0]\", \"['2013-05-13', 61]\"";
var json = raw.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
myData = [];
var parsed = JSON.parse(json);
for(var i = 0, len=parsed.length; i < len; ++i ) {
var date = new Date(parsed[i][0]);
myData.push( {
date: date,
day: date.getDay(),
count: parsed[i][1]
});
}
var mySundaysTotal = myData.
filter(function(x) { return x.day == 0; }). //find sundays
map(function(x) { return x.count; }). //get an array of the counts
reduce(function(x,y) { return x+y; }, 0); //sum the results
console.log(mySundaysTotal);
在行动中看到它:http://jsfiddle.net/tztLe/1/