检查数组中的项目是否连续但在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
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话