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

jap*_*hey 10 javascript arrays jquery

假设我有一个包含值 [1,2,3,6,7] 的数组。

如何检查数组是否包含 3 个连续的数字。例如,上面的数组包含 [1,2,3],因此这将在我的函数中返回 false。

        var currentElement = null;
        var counter = 0;

        //check if the array contains 3 or more consecutive numbers:
        for (var i = 0; i < bookedAppArray.length; i++) {
            if ((bookedAppArray[i] != currentElement) && (bookedAppArray[i] === bookedAppArray[i - 1] + 1)) {

                if (counter > 2) {
                    return true;
                }

                currentElement = bookedAppArray[i];
                counter++;
            } else {
                counter = 1;
            }
        }

        if(counter > 2){
            return true;
        } else{
            return false;
        }
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 7

这个解决方案

  • 检查数组的长度是否大于2
  • 从位置 2 开始迭代数组
  • 获取索引之前位置 2 和 1 之间的差值,
  • 检查绝对差值是否为1
  • 检查位置 1 之前和索引处之间的差异是否等于差异,
  • 如果是,则返回 false,因为找到了连续的元素。
  • 如果没有,则将索引增加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
Run Code Online (Sandbox Code Playgroud)

  • 哦,我重新阅读了最初的问题...调用 Continuous() 并在实际连续时收到 false 有点违反直觉,但明白了,谢谢 (2认同)