获得最高数组值的其他方法

use*_*206 5 javascript

我是一个相对较新的JavaScript,我试图通过if语句专门讨论ES6语法.我可以创建简单的ES6函数,如:

function test(a,c) {
return a+c;
}
[3,8,-4,3].reduce(test);
Run Code Online (Sandbox Code Playgroud)

但是,如果我想添加if语句,我无法使用ES6语法 - 例如:

function maxValue(a,c) {
if (c >= a) { a == c }
}
[3,8,-4,3].reduce(maxValue);
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用Math方法通过以下方式获得结果:

var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // returns 306
Run Code Online (Sandbox Code Playgroud)

但我想知道如何正确使用新的ES6语法.我试图在filter,reduce,map和forEach中添加if语句来实现数组中的最高值并且遇到困难.

任何有关初学者材料的帮助,建议或链接都​​将非常感谢,谢谢.

Nin*_*olz 5

您可以使用条件运算符检查更大的数字.

const max = (a, b) => a > b ? a : b;

console.log([3, 8, -4, 3].reduce(max));
Run Code Online (Sandbox Code Playgroud)

如果数组只有一个元素,则此方法不起作用.在这种情况下,您可以使用非常低的数字作为起始值并检查给定的值.

const max = (a, b) => a > b ? a : b;

console.log([3].reduce(max, -Infinity));
Run Code Online (Sandbox Code Playgroud)

换一种方式,不反复,你可以使用Math.max传播的语法...,它把数组作为参数调用函数的元素.

console.log(Math.max(...[3, 8, -4, 3]));
Run Code Online (Sandbox Code Playgroud)


Nik*_*wal 5

为了使代码正常工作,您需要进行2次更改

  • 就像简单的情况一样,您需要确保返回值。因为with return函数返回的值将是undefined,因此,不正确的计算
  • == 用于比较,用于分配,您需要使用 =

function maxValue(a,c) {
    if (c >= a) { a = c }
    return a;
}
console.log([3,8,-4,3].reduce(maxValue));
Run Code Online (Sandbox Code Playgroud)


bar*_*san 5

在ES6中,您可以使用解构语法.
Math.max(...array)是ES6相当于Math.max.apply(Math, array).

var array = [267, 306, 108];
var largest = Math.max(...array);
console.log(largest)
Run Code Online (Sandbox Code Playgroud)