javascript 获取数组的一个元素与前一个元素之间的差异

javascript Get the difference between an element of an array and the previous one

假设我有一个毫秒值数组,如下所示:

   const array = [
     1633236300000,
     1633244100000,
     1633248000000,
     1633252500000,
     1633287600000,
     1633291500000
   ]

如何获取数组元素与前一个元素之间的差异?

通过从第 2 个元素(索引 1)到末尾切片创建一个新数组,并将其映射。使用索引 (i) 从原始数组中取出一个项目,然后从当前项目 (t) 中减去它。

const array = [1633236300000,1633244100000,1633248000000,1633252500000,1633287600000,1633291500000]

const diff = array.slice(1)
  .map((t, i) => t - array[i])
  
console.log(diff)

获取项目在数组中的索引,然后从当前索引处减去前一个索引处的项目:

const array = [
  1633236300000,
  1633244100000,
  1633248000000,
  1633252500000,
  1633287600000,
  1633291500000
]


const num = 1633291500000;

const diff = num - array[array.indexOf(num) - 1];

console.log(diff)

1) 您可以使用旧式 for 循环,起始索引为 1

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = [];
for (let i = 1; i < array.length; ++i) {
  result.push(array[i] - array[i - 1]);
}

console.log(result);

2) 你也可以用map with slice

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = array.map((n, i, src) => n - (src[i - 1] ?? 0)).slice(1);

console.log(result);

3)这里也可以用reduce

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = array.reduce((acc, curr, i, src) => {
  if (i !== 0) acc.push(curr - src[i - 1]);
  return acc;
}, []);

console.log(result);

像这样:

function getDiff (n) {
  if (array.indexOf(n) === 0) return 'no previous time'
  return n - array[array.indexOf(n) - 1]
}

const d = getDiff(array[0])
console.log(d)