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

假设我有一个包含值[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  2) { return true; } currentElement = bookedAppArray[i]; counter++; } else { counter = 1; } } if(counter > 2){ return true; } else{ return false; } 

从逻辑上思考,这应该像迭代数组一样简单,只需检查当前数据之前的两个索引。

只需将1添加到上一个索引,将2添加到前一个索引之前,它们应该都是相同的,就像这样

 function hasThree(arr) { var res = false; arr.forEach(function(item, index) { var l1 = arr[index - 1], // get previous l2 = arr[index - 2]; // get the one before the previous if ( l1 && l2 ) { // if two previous exist // add 1, and then 2, and see if all are equal if ( item === l1 + 1 && item === l2 + 2 ) res = true; } }); return res; } 

小提琴

有趣的问题。 这是我的尝试。

 function cons(ar) { var cnt = 0; ar.forEach(function (i, idx) { if (idx > 0) { if (i == (ar[idx - 1] + 1)){ cnt++; } else { if (cnt < 2) cnt = 0; } } }); return cnt < 2; } console.log('expected true', cons([1, 2, 5, 6, 9])); console.log('expected false', cons([0, 2, 3, 4, 6, 9])); console.log('expected false', cons([1, 2, 3, 4, 6, 9])); 

这个解决方案

  • 检查数组的长度是否大于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]) + '
'); // true document.write(consecutive([2, 4, 6]) + '
'); // true document.write(consecutive([9, 8, 7]) + '
'); // false document.write(consecutive([1, 2, 3, 6, 7]) + '
'); // false document.write(consecutive([1, 2, 3, 4, 5]) + '
'); // false

尝试使用Array.prototype.some()Array.prototype.filter()

 var arr1 = [1, 2, 3, 9, 8, 7]; var arr2 = [1, 2, "a", 3]; var check = function(a) { // for each element in array `a` return !a.some(function(item, index) { // slice next three elements, including current element `item` from `a` array var next = a.slice(index, 3); console.log(next); // if next three items in array `a` are type `Number` // return `false`, else return `true` return next.filter(Number).length === 3 ? true : false }) }; // each item in `arr1` returns `false` , where item is followed // by two numbers // `arr2` returns `true` , where item is not followed by two numbers console.log(check([1,2,3]), check(arr1), check(arr2)) // `false`, `false`, `true`