数组能否形成连续序列 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 8:44:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字数组,并检查数组的元素是否可以重新排列以形成数字序列。

例如 −

如果数组是 −

const arr = [3, 1, 4, 2, 5];

那么输出应该是 −

true

示例

以下是代码 −

const arr = [3, 1, 4, 2, 5];
const canBeConsecutive = (arr = []) => {
   if(!arr.length){
      return false;
   };
   const copy = arr.slice();
   copy.sort((a, b) => a - b);
   for(let i = copy[0], j = 0; j < copy.length; i++, j++){
      if(copy[j] === i){
         continue;
      };
      return false;
   };
   return true;
};
console.log(canBeConsecutive(arr));

输出

以下是控制台中的输出 −

true

相关文章


有用资源