检查数组中的项目是否连续但在JavaScript中没有排序
我们需要编写一个JavaScript函数,该函数将Numbers数组作为第一个参数,并将数字(例如n)作为第二个参数。
我们的函数应检查数组中是否存在n序列(作为第二个参数)或更多个连续数字,但不对数组进行排序。
例如,如果我们的输入数组是-
const arr = [0, 4, 6, 5, 9, 8, 9, 12]; const n = 3;
然后我们的函数应该返回true,因为数组中存在三个连续的数字4、5和6。
示例
为此的代码将是-
const arr = [0, 4, 6, 5, 9, 8, 9, 12];
const n = 3;
const findSequence = (arr, num) => {
if(num > arr.length){
return false;
};
let count = 1;
for(let i = 0; i < arr.length; i++){
let el = arr[i];
while(arr.includes(++el)){
count++;
if(count === num){
return true;
};
};
count = 1;
};
return false;
};
console.log(findSequence(arr, n));
console.log(findSequence(arr, 4));输出结果
控制台中的输出将是-
true false