首頁  >  問答  >  主體

使用 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 天前304

全部回覆(2)我來回復

  • P粉846294303

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

    本來打算提出同樣的建議,也給程式碼提供了一點現代語法,所以Unmitigated打敗了我,但是可以使用map

    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
  • 取消回覆