Javascript 数组 = 添加缺失的日期
我有一些自行车店全天销售的数据,我们正在通过循环推送这些数据来构建一个数组。
我们的代码看起来像
var sales_array = [];
for (var i = 0; i < data_feed.length; i++)
{
var sales_values = Object.values(data_feed[i]);
sales_values = sales_values[0].split(";");
var date = sales_values[0];
var sales = sales_values[10];
if(sales != '') { sales_array.push(date+','+sales); }
}
这样效果很好,输出看起来像这样
"2022-02-07T16:20:00+00:00,20"
"2022-02-08T09:18:00+00:00,4500"
"2022-02-08T14:25:00+00:00,210"
"2022-02-09T11:21:00+00:00,100"
问题是,如果有几天商店关门并且没有进行销售,我们最终会在输出中丢失日期
例如,在2 月 27 日我们是开放的,但在 28 日和 1 日我们关闭了,并在 2 日重新开放,所以我们最终得到了
"2022-02-27T16:45:00+00:00,3000"
"2022-02-27T17:10:00+00:00,450"
-----MISSING-----
"2022-03-02T08:29:00+00:00,1000"
"2022-03-02T15:54:00+00:00,550"
如何更改循环代码,所以即使缺少日期,它也会将其添加到与 0销售价值,所以上面看起来像
"2022-02-27T16:45:00+00:00,3000"
"2022-02-27T17:10:00+00:00,450"
"2022-02-28T00:00:00+00:00,0"
"2022-03-01T00:00:00+00:00,0"
"2022-03-02T08:29:00+00:00,1000"
"2022-03-02T15:54:00+00:00,550"
I have some data of our bike shop sales throughout the day, and we are pushing that data through a loop to build up an array.
Our code looks like
var sales_array = [];
for (var i = 0; i < data_feed.length; i++)
{
var sales_values = Object.values(data_feed[i]);
sales_values = sales_values[0].split(";");
var date = sales_values[0];
var sales = sales_values[10];
if(sales != '') { sales_array.push(date+','+sales); }
}
And this works great, with an output looking something like
"2022-02-07T16:20:00+00:00,20"
"2022-02-08T09:18:00+00:00,4500"
"2022-02-08T14:25:00+00:00,210"
"2022-02-09T11:21:00+00:00,100"
The problem is, if there's a couple of days when the shop is closed and no sales take place, we end up with missing dates in our output
For example, on the 27th Feb we were open, but on the 28th and 1st we were closed, and reopened on the 2nd, so we ended up with
"2022-02-27T16:45:00+00:00,3000"
"2022-02-27T17:10:00+00:00,450"
-----MISSING-----
"2022-03-02T08:29:00+00:00,1000"
"2022-03-02T15:54:00+00:00,550"
How can we change our loop code, so even if there is a date missing, it'll add it in with a 0 sale value, so the above would look like
"2022-02-27T16:45:00+00:00,3000"
"2022-02-27T17:10:00+00:00,450"
"2022-02-28T00:00:00+00:00,0"
"2022-03-01T00:00:00+00:00,0"
"2022-03-02T08:29:00+00:00,1000"
"2022-03-02T15:54:00+00:00,550"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
data_feed
变量就像中添加了一些代码:
我在你的结果
asumming
data_feed
variable likei added some codes inside yours
results:
添加这些代码
add these code