如何在JavaScript数组中对对象的time属性进行减法运算
计算数组中两个时段的time属性差值问题
错误原因分析
- 直接用
periods[8] - periods[7]无效,因为periods[8]和periods[7]是数组中的对象,对象无法直接进行减法运算,结果会是NaN。 periods.time无效,因为periods是数组,数组本身没有time属性,因此返回undefined。
正确实现代码
要计算差值,需要先获取对应位置的对象,再访问其time属性进行运算:
// 分别获取第7、8时段的time数值 const seventhTime = periods[7].time; const eighthTime = periods[8].time; // 计算差值 const diff = eighthTime - seventhTime; console.log(diff); // 输出 0.93
也可以简化为一行代码:
console.log(periods[8].time - periods[7].time); // 0.93
关键概念说明
- 你的
periods是一个数组,数组的索引从0开始计数,所以第7个时段对应索引7,第8个时段对应索引8。 - 数组中的每个元素是对象,要获取对象的属性值,必须通过
对象.属性名的方式(比如periods[7].time),这样才能拿到具体的数值用于计算。
内容的提问来源于stack exchange,提问作者OxidizedToast
相关产品推荐
相关产品推荐

