--- title: Math.max() slug: Web/JavaScript/Reference/Global_Objects/Math/max tags: - JavaScript - Math translation_of: Web/JavaScript/Reference/Global_Objects/Math/max --- <div>{{JSRef}}</div> <p><code><strong>Math.max()</strong></code> 函数返回一组数中的最大值。</p> <p>{{EmbedInteractiveExample("pages/js/math-max.html")}}</p> <h2 id="Syntax" name="Syntax">语法</h2> <pre class="syntaxbox"><code>Math.max(<em>value1</em>[,<em>value2</em>, ...]) </code></pre> <h3 id="Parameters" name="Parameters">参数</h3> <dl> <dt><code>value1, value2, ...</code></dt> <dd>一组数值</dd> </dl> <h3 id="返回值">返回值</h3> <p>返回给定的一组数字中的最大值。如果给定的参数中至少有一个参数无法被转换成数字,则会返回 {{jsxref("NaN")}}。</p> <h2 id="Description" name="Description">描述</h2> <p>由于 <code>max</code> 是 <code>Math</code> 的静态方法,所以应该像这样使用:<code>Math.max()</code>,而不是创建的 <code>Math</code> 实例的方法(<code>Math</code> 不是构造函数)。</p> <p>如果没有参数,则结果为 - {{jsxref("Infinity")}}。</p> <p>如果有任一参数不能被转换为数值,则结果为 {{jsxref("NaN")}}。</p> <h2 id="Examples" name="Examples">示例</h2> <h3 id="Example_Using_Math.max" name="Example:_Using_Math.max">使用 <code>Math.max()</code></h3> <pre>Math.max(10, 20); // 20 Math.max(-10, -20); // -10 Math.max(-10, 20); // 20</pre> <p>下面的方法使用 {{jsxref("Global_Objects/Function/apply", "apply")}} 方法寻找一个数值数组中的最大元素。<code>getMaxOfArray([1,2,3])</code> 等价于 <code>Math.max(1, 2, 3)</code>,但是你可以使用 <code>getMaxOfArray</code> ()作用于任意长度的数组上。</p> <pre class="brush:js">function getMaxOfArray(numArray) { return Math.max.apply(null, numArray); } </pre> <p>或者通过使用最新的扩展语句{{jsxref("Operators/Spread_operator", "spread operator")}},获得数组中的最大值变得更容易。</p> <pre class="brush: js">var arr = [1, 2, 3]; var max = Math.max(...arr); </pre> <h2 id="规范">规范</h2> <table class="standard-table"> <tbody> <tr> <th scope="col">规范版本</th> <th scope="col">规范状态</th> <th scope="col">注解</th> </tr> <tr> <td>{{SpecName('ES1')}}</td> <td>{{Spec2('ES1')}}</td> <td>Initial definition. Implemented in JavaScript 1.0.</td> </tr> <tr> <td>{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}</td> <td>{{Spec2('ES5.1')}}</td> <td></td> </tr> <tr> <td>{{SpecName('ES6', '#sec-math.max', 'Math.max')}}</td> <td>{{Spec2('ES6')}}</td> <td></td> </tr> <tr> <td>{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}</td> <td>{{Spec2('ESDraft')}}</td> <td></td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{Compat("javascript.builtins.Math.max")}}</p> <h2 id="See_also" name="See_also">相关链接</h2> <ul> <li>{{jsxref("Math.min()")}}</li> </ul>