在 JavaScript 中查找两个数组的连续性
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 17:48:17
我们需要编写一个 JavaScript 函数,该函数接受两个数字数组。如果两个数组在合并和打乱后可以形成一个连续的序列,则该函数应返回 true,否则返回 false。
例如:如果数组为 −
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
则输出应为 true。
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr1 = [4, 6, 2, 9, 3];
const arr2 = [1, 5, 8, 7];
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if(combined.length < 2){
return true;
};
combined.sort((a, b) => a-b);
const commonDifference = combined[0] - combined[1];
for(let i = 1; i < combined.length-1; i++){
if(combined[i] - combined[i+1] === commonDifference){
continue;
};
return false;
};
return true;
};
console.log(canFormSequence(arr1, arr2));
输出
控制台中的输出将是 −
true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

