You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:23:19