Javascript Math.max和Math.min如何实际工作?

我真的很好奇这些功能是如何运作的?我知道有很多关于如何使用它们的问题,我已经知道如何使用它们,但我无法在任何地方找到如何实际在数组上实现此功能,例如,如果没有这样的功能?如果没有帮助者,你会如何编写这样的函数

解决方法

我们来看看规范(可以/应该帮助您实现!)

ECMAScript 1st Edition (ECMA-262)(Math.max / min的初始定义)中,我们看到以下内容

15.8.2.11 max(x,y)
Returns the larger of the two arguments.
    • If either argument is NaN,the result is NaN.
    • If x>y,the result is x.
    • If y>x,the result is y.
    • If x is +0 and y is +0,the result is +0.
    • If x is +0 and y is −0,the result is +0.
    • If x is −0 and y is +0,the result is +0.
    • If x is −0 and y is −0,the result is −0.

15.8.2.12 min(x,y)
    Returns the smaller of the two arguments.
    • If either argument is NaN,the result is NaN.
    • If x<y,the result is x.
    • If y<x,the result is −0.
    • If x is −0 and y is +0,the result is −0.
    • If x is −0 and y is −0,the result is −0.

该规范的后续版本为我们提供:

ECMAScript 5.1

15.8.2.11 max ( [ value1 [,value2 [,… ] ] ] )

    Given zero or more arguments,calls ToNumber on each of the arguments and returns the largest of the resulting values.

    • If no arguments are given,the result is −∞.
    • If any value is NaN,the result is NaN.
    • The comparison of values to determine the largest value is done as in 11.8.5 except that +0 is considered to be larger than −0.

    The length property of the max method is 2.

15.8.2.12 min ( [ value1 [,calls ToNumber on each of the arguments and returns the smallest of the resulting values.

    • If no arguments are given,the result is +∞.
    • If any value is NaN,the result is NaN.
    • The comparison of values to determine the smallest value is done as in 11.8.5 except that +0 is considered to be larger than −0.

    The length property of the min method is 2.

可在此处找到对11.8.5的引用:The Abstract Relational Comparison Algorithm

ECMAScript 2015

20.2.2.24 Math.max ( value1,value2,…values )

    Given zero or more arguments,the result is NaN.
    • The comparison of values to determine the largest value is done using the Abstract Relational Comparison algorithm (7.2.11) except that +0 is considered to be larger than −0.

    The length property of the max method is 2.

20.2.2.25 Math.min ( value1,the result is NaN.
    • The comparison of values to determine the smallest value is done using the Abstract Relational Comparison algorithm (7.2.11) except that +0 is considered to be larger than −0.

The length property of the min method is 2.

再次,7.2.11可以在这里找到:Abstract Relational Comparison

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...