gpt4 book ai didi

javascript - 初值不定时小于但大于的比较逻辑

转载 作者:行者123 更新时间:2023-12-04 10:52:30 24 4
gpt4 key购买 nike

下面的代码是一个涉及moment.js 的大型项目的一小部分,但moment 不是必需的。我正在使用 UTC 日期,我可以使用简单的值比较。我正在寻找返回该值之后的索引,但它是所有值中最低的(低于 uc)。换句话说,大于 faketimenow 的最小值.由于这些值是无序的,因此都需要根据最低值检查它们。

下面的代码有效,但我很好奇这是否可以在没有占位符的情况下构建 uc变量来存储初始的起始变量。如果我正在寻找最大但不确定如何与具有不确定初始值的值进行比较,这将很容易。我尝试使用 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]);

最佳答案

您可以采用单循环方法而不进行排序,并返回高于给定值的最小值的索引。

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]);


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]);

关于javascript - 初值不定时小于但大于的比较逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416212/

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