且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript检查数组中的项是否连续

更新时间:2022-11-01 19:37:59

此解决方案


  • 检查数组的长度是否大于 2

  • 从位置2迭代数组

  • 获取索引前位置2和1之间的差异,

  • 检查绝对差异是 1

  • 检查位置1之前和指数之间的差异是否等于差异,

  • 如果是这样,它返回false,因为找到了连续的元素。

  • 如果没有,增加索引 1

  • checks wheater the length of the array is greater than 2,
  • iterates over the array from position 2
  • gets the difference between position 2 and 1 before the index,
  • checks if the absolute difference is 1
  • checks the difference between position 1 before and at the index is equal the difference,
  • and if so, it returns false, because consecutive elements are found.
  • if not, increment index by 1

function consecutive(array) {
    var i = 2, d;
    while (i < array.length) {
        d = array[i - 1] - array[i - 2];
        if (Math.abs(d) === 1 && d === array[i] - array[i - 1]) {
            return false;
        }
        i++;
    }
    return true;
}

document.write(consecutive([1]) + '<br>');             // true
document.write(consecutive([2, 4, 6]) + '<br>');       // true
document.write(consecutive([9, 8, 7]) + '<br>');       // false
document.write(consecutive([1, 2, 3, 6, 7]) + '<br>'); // false
document.write(consecutive([1, 2, 3, 4, 5]) + '<br>'); // false