我有四个数字,它们可能相同,但也很可能不同。基本上我希望这个函数选择的数量不相等,但如果不相等,则选择最低的一个,如果有两个相同,则只选择其中一个并继续使用。
例如,我有 3434
、3396
、3414
和 3374
。好吧,我希望函数返回给我,如果它们都相同,则为 0
,对于第一个,则为 1
,依此类推。因此在这种情况下我需要返回 4
。
但如果数字是 321
、576
、812
和 321
,它会返回给我 1
。
我已经这样做了几天了,但我似乎找不到任何方法来做我需要做的事情。有人知道可以让这项工作神奇地进行的东西吗?谢谢!
编辑 我的方法让我做一些类似于创建数组对其进行排序并尝试使用最后结果的事情,但是当我对数组进行排序时,键会变得困惑,所以我不知道它属于哪个值
var choices = new Array();
choices[1] = parseInt(value1);
choices[2] = ...
choices = choices.sort();
//and then I ran into the problem that my keys being not starting
//with 0, it added an element which I was able to remove by doing this
choices = choices.splice(0,4);
然后我就被困在那里了
最佳答案
这是回答您的问题的旅程的开始。正如其他人指出的那样,这段代码并不能处理您提到的所有情况;这是故意的。
How can I pick the lowest number from a list of numbers?
手卷方式; O(n)
一次通过:
var myList = [3434, 3396, 3414, 3374];
var min = Infinity;
var minIndex = -1;
var current;
for (var i=0; i<myList.length; i++)
{
current = myList[i];
if (current < min)
{
min = current;
minIndex = i;
}
}
// the value you want is in minIndex
更加简洁;也是 O(n)
但两次遍历数组:
var min = Math.min.apply(null, myList);
var minIndex = myList.indexOf(min);
注意 Array.indexOf
在旧版 IE 中需要填充程序。
Basically I want this function to chose no number of they are equal
正如他们所说,这个练习留给读者。
关于javascript - 如何从数字列表中选出最小的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241586/