我正在尝试根据月份对数组进行排序。我的示例输入:
var result = [{date: '2017/01/23', total: 364.59999999999997},
{date: '2017/04/07', total: 32.7},
{date: '2017/04/25', total: 42.99999999999999},
{date: '2017/07/01', total: 15.37},
{date: '2017/12/02', total: 33.980000000000004},
{date: '2017/03/26', total: 50.6},
{date: '2017/03/13', total: 65.1},
{date: '2017/10/13', total: 337.5},
{date: '2017/07/09', total: 50.2},
{date: '2017/11/02', total: 75}];
我想做的是首先提取月份,然后如果它们来自同一个月,我想总结总数。
var priceData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for(var i = 0; i < result.length; i++){
var str = result[i].date;
var month = str.substr(5, 2);
if(month == '01'){ monthIndex = 0;}
else if(month == '02'){ monthIndex = 1;}
else if(month == '03'){ monthIndex = 2;}
else if(month == '04'){ monthIndex = 3;}
else if(month == '05'){ monthIndex = 4;}
else if(month == '06'){ monthIndex = 5;}
else if(month == '07'){ monthIndex = 6;}
else if(month == '08'){ monthIndex = 7;}
else if(month == '09'){ monthIndex = 8;}
else if(month == '10'){ monthIndex = 9;}
else if(month == '11'){ monthIndex = 10;}
else if(month == '12'){ monthIndex = 11;}
if(priceData[monthIndex] == 0){
priceData.splice(monthIndex, 0, result[i].total);
}else{
var amount = priceData[monthIndex];
var finalizedAmount = amount + result[i].total;
priceData.splice(monthIndex, amount, finalizedAmount);
}
console.log('date ' + result[i].date + ' ' + result[i].total);
}
首先,我检查priceData的索引是否为0。如果为0,我只需使用splice()替换它。如果没有,我得到以前的金额,然后与新的金额相加,然后替换它。但是,通过上面的代码,我得到的输出如下:
364.59999999999997
0
115.69999999999999
NaN
NaN
NaN
最佳答案
我认为如果将日期字符串解析为 native 日期对象,可以简化代码。您可以使用 getMonth将返回月份的 0 到 11 之间的整数。
另外,我用的是ES6 Array.fill()函数,因为现在是 2017 年,我们不需要循环用零填充数组:)
以下是我对问题的解决方案:
const result = [
{date: '2017/01/23', total: 364.59999999999997},
{date: '2017/04/07', total: 32.7},
{date: '2017/04/25', total: 42.99999999999999},
{date: '2017/07/01', total: 15.37},
{date: '2017/12/02', total: 33.980000000000004},
{date: '2017/03/26', total: 50.6},
{date: '2017/03/13', total: 65.1},
{date: '2017/10/13', total: 337.5},
{date: '2017/07/09', total: 50.2},
{date: '2017/11/02', total: 75}
];
const priceData = new Array(12).fill(0);
result.forEach(o => {
const monthIndex = new Date(o.date).getMonth();
priceData[monthIndex] += o.total;
});
console.log(priceData);
关于JavaScript 使用 splice() 对数组进行排序,结果为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517559/