首页  >  问答  >  正文

使用 apply 中的方法

要找到数组的最大值,一个简单的方法是

Math.max.apply(null, myArray)

但是,假设 myArray 包含复数,并且每个复数都有一个方法 magnitude 来计算复数的长度,是否有一种简单的方法可以找到 myArray 中条目的最大值?我当然可以做一个 loop 或一个函数,但我的猜测是 javascript 有一个很好的单行解决方案......

这是包含所有元素的简短代码片段:

function Complex(re, im) {
  this.real = re;
  this.imag = im;
}

Complex.prototype.magnitude = function() {
  return Math.sqrt(this.real * this.real + this.imag * this.imag);
};

var a = new Array(1, 2, 3);
ra = Math.max.apply(null, a); // works fine

var b = new Array(new Complex(1, 2), new Complex(1, 3), new Complex(1, 4));
rb = Math.max.apply(null, b)

console.log(ra)
console.log(rb) //NaN without surprise

P粉718730956P粉718730956180 天前303

全部回复(2)我来回复

  • P粉846294303

    P粉8462943032024-04-04 11:41:14

    本来打算提出同样的建议,也给代码提供了一点现代语法,所以Unmitigated打败了我,但是可以使用ma​​p

    class Complex {
    
      constructor(real, imag) {
        this.real = real;
        this.imag = imag;
      }
    
      magnitude() {
        return Math.sqrt(this.real * this.real + this.imag * this.imag);
      };
    }
    
    let a = [1, 2, 3]
    ra = Math.max(...a) // works fine
    
    var b = [new Complex(1, 2), new Complex(1, 3), new Complex(1, 4)];
    rb = Math.max(...b.map(x => x.magnitude()));
    
    console.log(ra)
    console.log(rb) // works now

    是的,您可以使用扩展语法代替 apply,使用括号代替 new Array,并且您可以使用类语法,因为 Complex 实际上是一个类。< /p>

    回复
    0
  • P粉306523969
  • 取消回复