本文介绍了Javascript检查数组中的项是否连续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含值[1,2,3,6,7]的数组。
Say I have an array which holds the values [1,2,3,6,7].
如何检查数组以查看它是否成立连续3个号码。例如,上面的数组保持[1,2,3],所以这将在我的函数中返回false。
How can I check the array to see if it holds 3 consecutive numbers. For example, the array above holds [1,2,3] so this would return false in my function.
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;
}
推荐答案
此解决方案
- 检查数组的长度是否大于
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
这篇关于Javascript检查数组中的项是否连续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!