2013-07-16 83 views
0

我有一些这样的数组,数组中的数字表示插槽编号 slots1 = {3,4,5,6} slots2 = {1,2,3,4,5 ,6} slots3 = {8,9,10}
我在查找所选槽是否连续。
前两个数组给出正确的最小值,最大值。 但第三个数组给出最小= 10,最大= 9。 如何纠正它? 我发现这样在javascript数组中找到最小值最大值

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]; 
        } 
      }    
     } 
+0

你应该申报和你的循环...... – jahroy

+0

你有一个印刷错误,检查**插槽[S] **,但迭代** no_slots前初始化'slots_max' ** – udalmik

+0

@mudalov - 实际上,'no_slots'看起来就像是数组的长度。 's'是正确的迭代器变量。据推测,for循环之前的行看起来像这样:'var no_slots = slots.length;' – jahroy

回答

3

最大值使用JS Math对象:

对于最低:Math.min.apply(null,slots);
对于最大:Math.max.apply(null,slots);

+0

非常感谢。 – gayathri

1

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

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

有关更多详细信息,请参见this answer

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

+0

我们真的需要其他条件吗?如果(内部)独立,我们可以做到这一点。 –

相关问题