返回数组中的最小数字而不使用Math

时间:2014-09-26 01:43:25

标签: javascript

我需要创建一个返回数组中最小数字的函数,我似乎无法解决这个问题而这里的其他问题根本没有帮助,因为他们给出了代码的答案i从来没有见过,所以我有这个,但它总是只返回" 0"不是80,所以你可以帮我解决我的代码吗?



var value = [100, 90, 100, 80];

function lowestGrade(a) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] < a.length);
    value = i; {
      return (value);
    }
  }
}

document.write(lowestGrade(value));
&#13;
&#13;
&#13;   

6 个答案:

答案 0 :(得分:1)

正如已经提到的,有内置的方法来处理这个问题。但是,我假设这是某种功课问题。

var array = [90, 1, 77, -5, 101];

function lowest(arr) {
  //Assume first is lowest
  var low = arr[0];

  for (var i = 0; i < arr.length; i++) {
    //If this isn't lower, swap
    if (low > arr[i]) {
      low = arr[i];
    }
  }

  //Will always contain lowest number
  return low;
}

document.write(lowest(array));

答案 1 :(得分:1)

问题在这里;

function lowestGrade(a) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] < a.length); // < -- this is an if statement which has no effect
    value = i;  // <-- this just set the value to the loop index i 
    {
      return (value);   // << -- this returns at the first loop where i is zeo 
    }
  }
}

相反,做;

&#13;
&#13;
var value = [100, 90, 100, 80];
function lowestGrade(a) {
  var lowest = a[0];
  for (var i = 0; i < a.length; i++) {
    if (a[i] < lowest) 
       lowest = a[i];
  }
  return lowest;
}

document.write(lowestGrade(value));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

var value = [100, 90, 100, 80];

function lowestGrade(a) {
var lowestNum = a[0]; // Set it to first element
  for (var i = 1; i < a.length; i++) { //loop through array, starting at first element if length is greater than 1
    if (a[i] < lowestNum)
        lowestNum = a[i]; //if the array value is lower than your variable, set your variable to it
  }
  return lowestNum;
}

document.write(lowestGrade(value));

答案 3 :(得分:0)

试试这个:

var value = [100, 90, 100, 80];
lowestGrade(value);

function lowestGrade (value) 
{
    var lowest;
    for(var i = 0, cnt = value.length; i<cnt; i++){
        if(typeof lowest === 'undefined') {
           lowest = value[i]
        } else {
            if(value[i] < lowest){
                lowest = value[i];
            }
        }
    }

    console.log(lowest);
}

小提琴here

答案 4 :(得分:0)

由于您特别要求在Javascript中不使用Math对象,因此我在Stackoverflow中找到了一个以您希望的方式解决它的答案:

function mymax(a)
{
    var m = -Infinity, i = 0, n = a.length;

    for (; i != n; ++i) {
        if (a[i] > m) {
            m = a[i];
        }
    }

    return m;
}

我没有这个答案,所以请查看此链接以查看原始作者的答案:https://stackoverflow.com/a/13794386/44852

答案 5 :(得分:0)

如果您没有学习如何排序,可以使用原生reduce功能。

var value = [100, 90, 100, 80];
var min = value.reduce(function (pv,cv) {
    return pv > cv?cv:pv
});
document.write(min);