简体   繁体   English

当初始值不确定时比较逻辑小于但大于

[英]Comparison logic less than but more than when initial value is indeterminate

The code below is a sliver of a larger project involving moment.js, but moment isn't necessary.下面的代码是涉及 moment.js 的更大项目的一小部分,但 moment 不是必需的。 I'm working in UTC dates and I can use a simple value comparison.我在 UTC 日期工作,我可以使用简单的值比较。 I'm looking to return the index that value is after but is the lowest of all values (lower than uc).我希望返回该值之后的索引,但它是所有值中最低的(低于 uc)。 In other words, lowest value that is more than faketimenow .换句话说,最低值大于faketimenow Since these values are out of order, they all need to be checked against the lowest value.由于这些值是乱序的,它们都需要对照最低值进行检查。

The code below works, but I'm curious if this can be built without a placeholder uc variable to store an initial starting variable.下面的代码有效,但我很好奇是否可以在没有占位符uc变量的情况下构建它来存储初始起始变量。 This would be easy if I was looking for greatest, but not certain how to compare against a value that has an indeterminate initial value.如果我正在寻找最大的,但不确定如何与具有不确定初始值的值进行比较,这将很容易。 I tried using arr[0] as the starting value but that is passed through since its unluckily the least number.我尝试使用 arr[0] 作为起始值,但由于不幸的是它是最少的数字,因此它被传递了。

// random range for demonstration purposes
var arr = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23];

var faketimenow = 10;

//initial index to use
var indextouse = 0;

// using a variable with initial start value that is ridiculously out of scope
var uc = 1000000000000;

for (i = 0; i < arr.length; i++) {
  console.log("i: " + i + " , faketimenow: " + faketimenow + " , indextouse: " + indextouse + ", uc: " + uc);
  if (arr[i] > faketimenow && arr[i] < uc) {
    uc = arr[i];
    indextouse = i;
  }
}

console.log(arr[indextouse]);

You can use Infinity as the initial value, everything is lower than that.您可以使用Infinity作为初始值,一切都低于此值。

But a simpler solution is to sort the array and then find the first element higher than faketimenow .但更简单的解决方案是对数组进行排序,然后找到第一个高于faketimenow元素。

 // random range for demonstration purposes var arr = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23]; var faketimenow = 10; arr.sort((a, b) => a - b); var uc = arr.find(n => n > faketimenow); console.log(uc);

You could take a single loop approach without sorting and return the index of the smallest value above the given value.您可以采用单循环方法而不进行排序并返回给定值之上的最小值的索引。

 var array = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23], value = 10, index = -1, i; for (i = 0; i < array.length; i++) { if (array[i] > value && (index === -1 || array[i] < array[index])) index = i; } console.log(array[index]);

With reduce .随着reduce

 var array = [1, 2, 3, 4, 100, 17, 22, 15, 13, 11, 23], value = 10, index = array.reduce((r, v, i, a) => v > value && (r === -1 || v < a[r]) ? i : r, -1); console.log(array[index]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM