在javascript数组中找到最小值

时间:2013-07-16 07:41:31

标签: javascript

我有一些像这样的数组,数组中的数字代表插槽号        slots1 = {3,4,5,6}        slots2 = {1,2,3,4,5,6}        slots3 = {8,9,10}
      我发现所选的插槽是否是连续的    前两个数组给出正确的最小值,最大值。   但第三个数组给出min = 10,max = 9。    怎么纠正呢? 我发现这样的最大价值

for(var s=0;s<no_slots;s++)//finding maximum value of slots array
        {    
             if(s == 0)
             { 
              var slots_max = slots[s];
             }
             else
             {
                    if(slots[s] > slots_max)
                    {
                      slots_max = slots[s];
                    }
             }              
        }  

3 个答案:

答案 0 :(得分:3)

使用JS Math对象:

至少:Math.min.apply(null,slots);
最大值:Math.max.apply(null,slots);

答案 1 :(得分:2)

我不确定为什么你的功能不适合你的第三种情况。你可能错过了像初始化或类似的东西愚蠢的东西。 因为我修改了你的一些代码,它正确地返回。你也可以缩短它。

var slots = [8, 9, 10]
var slots_max = slots[0];
for (var s = 0; s < slots.length; s++) //finding maximum value of slots array
{
   if (slots[s] > slots_max) {
         slots_max = slots[s];
      }
}
alert(slots_max);

Js Fiddle

答案 2 :(得分:1)

您可以尝试使用Javascript Math库查找最小/最大值。这应该返回正确的结果。

var min = Math.min.apply(null, slots3);
var max = Math.max.apply(null, slots3);

有关详细信息,请参阅this answer

相关问题