JavaScript - 构造一个新数组,其元素为输入数组中连续元素之间的差值
javascript libraryweb developmentfront end technologyobject oriented programming更新于 2025/12/5 15:40:17
假设我们有一个像这样的数字数组 −
const arr = [3, 5, 5, 23, 3, 5, 6, 43, 23, 7];
我们需要编写一个函数,接受一个这样的数组,并构造另一个数组,其元素为输入数组中连续元素之间的差值。
对于这个数组,输出将是 −
const output = [-2, 0, -18, 20, -2, -1, -37, 20, 16];
示例
以下是代码 −
const arr = [3, 5, 5, 23, 3, 5, 6, 43, 23, 7];
const consecutiveDifference = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr[i + 1]){
res.push(arr[i] - arr[i+1]);
};
};
return res;
};
console.log(consecutiveDifference(arr));
输出
以下是控制台中的输出 −
[ -2, 0, -18, 20, -2, -1, -37, 20, 16 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

