Javascript Math.max和Math.min如何实际工作? [英] How do Javascript Math.max and Math.min actually work?

查看:87
本文介绍了Javascript Math.max和Math.min如何实际工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am really curious how these functions actually work? I know there are a lot of questions about how to use these, I already know how to use them, but I couldn't find anywhere how to actually go about implementing this functionality on an array, for example, if there were no such functions? How would you code such a function if there were no helpers?

推荐答案

这是Chrome V8引擎中的Math.max代码。

Here is the Math.max code in Chrome V8 engine.

function MathMax(arg1, arg2) {  // length == 2
  var length = %_ArgumentsLength();
  if (length == 2) {
    arg1 = TO_NUMBER(arg1);
    arg2 = TO_NUMBER(arg2);
    if (arg2 > arg1) return arg2;
    if (arg1 > arg2) return arg1;
    if (arg1 == arg2) {
      // Make sure -0 is considered less than +0.
      return (arg1 === 0 && %_IsMinusZero(arg1)) ? arg2 : arg1;
    }
    // All comparisons failed, one of the arguments must be NaN.
    return NaN;
  }
  var r = -INFINITY;
  for (var i = 0; i < length; i++) {
    var n = %_Arguments(i);
    n = TO_NUMBER(n);
    // Make sure +0 is considered greater than -0.
    if (NUMBER_IS_NAN(n) || n > r || (r === 0 && n === 0 && %_IsMinusZero(r))) {
      r = n;
    }
  }
  return r;
}

这里是存储库。

这篇关于Javascript Math.max和Math.min如何实际工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆