功能选择最大的数字

时间:2016-09-23 02:48:52

标签: javascript arrays function

我正在尝试创建一个能够获取数组中最大数字的函数,但我似乎无法通过第一个数字。

function largestNumber(numbers) {
  var constant = 1;
    for(i = 0; i < numbers.length; i++) {
      if(numbers[i] > constant) {
          constant = numbers[i];
      }
      return constant;        
    }
}
var numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];

largestNumber(numbers);

4 个答案:

答案 0 :(得分:1)

您可以将[{3}}与展开运算符

一起使用

 function largestNumber(arr) {
   return Math.max(...arr);
 }
    
var numbers=[3,4,2,6,45,775,83,5,7];
largestNumber(numbers);

console.log(largestNumber(numbers));

答案 1 :(得分:0)

问题是,你早点回来了。

function largestNumber(numbers) {
  // return null by default
  var result = null;

  if (numbers.length) {
    // if there is a value in the array, return it by default
    result = numbers[0];
    for (i = 0; i < numbers.length; i++) {
      if (numbers[i] > result) {
        result = numbers[i];
      }
    } // <= you were returning too early
  }
  return result;
}

var numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];
largestNumber(numbers);

答案 2 :(得分:0)

这是一个返回到目前为止看到的最大数字的生成器:

function *max(array) {
  let result = -Infinity;
  for (let v of array) yield result = v > result ? v : result;
}

您可以通过获取最后一个元素来找到数组的最大值:

function last(array) { return array[array.length - 1]; }

const numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];

console.log(last([...max(numbers)]));

需要[...]将结果流从生成器转换为数组; Array.from也可以。

答案 3 :(得分:-1)

function largestNumber(numbers) {
    var constant = 1;
    for (i = 0; i < numbers.length; i++) {
        if (numbers[i] > constant) {
            constant = numbers[i];
        }
    }
    return constant;    // after iterating the entire array!
}
var numbers = [3, 4, 2, 6, 45, 775, 83, 5, 7];
console.log(largestNumber(numbers))