如何在TypeScript中从带时间戳的对象数组计算连续时长
TypeScript计算对象数组中连续元素的时长差值
假设你的数组元素都包含timestamp属性(这里假设为数字类型,比如毫秒时间戳),可以用以下几种方式实现类似Python中durations = myArray[1:]-myArray[:-1]的效果:
方法1:切片+Map(最贴近Python逻辑)
利用slice(1)获取从第二个元素开始的子数组,再通过map对应原数组的前序元素计算差值:
// 先定义类型约束(TypeScript特性) interface TimestampedObj { [key: string]: any; timestamp: number; } // 示例数组 const myArray: TimestampedObj[] = [ { attr1: 'val1', timestamp: 1620000000000 }, { attr2: 'val2', timestamp: 1620003600000 }, { attr3: 'val3', timestamp: 1620007200000 } ]; // 计算连续时长 const durations = myArray.slice(1).map((current, idx) => { return current.timestamp - myArray[idx].timestamp; }); // 输出:[3600000, 3600000](即每间隔1小时) console.log(durations);
方法2:Map+索引判断
直接遍历原数组,通过索引跳过第一个元素,计算当前元素与前一个元素的差值:
const durations = myArray.map((obj, idx) => { if (idx === 0) return null; return obj.timestamp - myArray[idx - 1].timestamp; }).filter(d => d !== null) as number[];
方法3:Reduce累加
用reduce遍历数组,逐步收集差值结果:
const durations = myArray.reduce((acc, current, idx) => { if (idx > 0) { acc.push(current.timestamp - myArray[idx - 1].timestamp); } return acc; }, [] as number[]);
注意事项
- 如果你的
timestamp是Date对象而非数字,需要先转换为时间戳:current.timestamp.getTime() - myArray[idx].timestamp.getTime() - 所有方法都会返回一个长度为原数组长度-1的差值数组,和Python的结果完全对应。
内容的提问来源于stack exchange,提问作者alpha027
相关产品推荐
相关产品推荐

