gpt4 book ai didi

javascript - 数组值按连续顺序排列

转载 作者:行者123 更新时间:2023-11-28 17:35:04 27 4
gpt4 key购买 nike

当函数为 true 时,我会构建一个带有计数器的数组。

因此,如果连续 3 次为真,则数组看起来像 [1,2,3]。如果该函数不为 true,则计数器中会有间隙,可能如下所示 [1,2,3,5]。

在另一个函数中,我需要确定数组长度是否 > 2 并且数组中的值是否按连续顺序排列。所以 [1,2,3] 它应该返回 true。如果 [1,2,3,5] 它应该返回 false。

我还没有发现任何有效的东西。任何有关可能解决方案的帮助将不胜感激。

我已经看到过这个(并且已经尝试过),但它不起作用。

Array.prototype.is_consecutive = (function () {
var offset = 0; // remember the last offset
return function () {
var start = offset, len = this.length;
for (var i = start + 1; i < len; i++) {
if (this[i] !== this[i - 1] + 1) {
break;
}
}
offset = i;
return this[start];
};
})();

最佳答案

如果您绝对可以依赖填充数组的算法,请遵循规定的规则

I build up an array with a counter when a function is true. So if it were true 3 times in a row, the array looks like [1,2,3]. If the function is not true there is a gap in the counter and could look like this [1,2,3,5].

然后你需要做的就是检查数组的最后一个元素是否与数组的长度相同:

var good = [1, 2, 3];
var bad = [1, 2, 3, 5];

var isValid = function(arr) {
return (arr.length > 2 && arr[arr.length - 1] === arr.length); // Thanks to Jonas W.
}
console.log(isValid(good));
console.log(isValid(bad));

关于javascript - 数组值按连续顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com