如何计算总小时数?
我正在尝试计算阵列的总小时数。阵列包含一系列会话,需要不同的时间来得出结论。我可能遇到的问题是小时字段是字符串。
这就是外观:
[
{ "id": 1,
"exercise": "1.1",
"name": "Session one",
"hours": "1"
},
{ "id": 2,
"exercise": "1.2",
"name": "Session two",
"hours": "4"
},
{ "id": 3,
"exercise": "1.3",
"name": "Session three",
"hours": "0,5"
}
]
总计应达到5,5小时。
我试图过滤阵列:
computed: {
hours(){
var hours = 0
this.oft.filter((item => {
hours += item.hours
}))
return hours
}
},
但是它返回了一个荒谬的高数字。
I'm trying to calculate the total amount of hours from an array. The array contains a series of sessions that take different time to conclude. The problem that I might have, is that the hour field is a string.
This is how it looks like:
[
{ "id": 1,
"exercise": "1.1",
"name": "Session one",
"hours": "1"
},
{ "id": 2,
"exercise": "1.2",
"name": "Session two",
"hours": "4"
},
{ "id": 3,
"exercise": "1.3",
"name": "Session three",
"hours": "0,5"
}
]
And the totalt should amount to 5,5 hours.
I have tried to filter the array:
computed: {
hours(){
var hours = 0
this.oft.filter((item => {
hours += item.hours
}))
return hours
}
},
But it returns a ridiculous high number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我观察到您的输入ID 3小时无法转换为呈现方式的数字coz,它应该为
0.5
而不是0,5
,并且如果您想要要查找总小时数,过滤器不是您的方法,您需要在给定数组上的单个值基库,但是过滤器返回新数组基础,您应该使用降低代码,就像这样。
I observed your input the id 3 hours couldn't be converted into a number coz of the way it is presented it should be
0.5
instead of0,5
and if you want to find the total number of hours filter is not your method you want single value base on given array but filter returns new array base on condition you should use reduce the code would be like this ``
您可以使用
降低
来知道
0,5
不是有效的数字,因此您必须用,
。<<<<
。 /代码>为了正确解析you can do it with
reduce
be aware that
0,5
is not a valid number so you have to replace,
with.
in order to parse it correctly