亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

使用 apply 中的方法
P粉718730956
P粉718730956 2024-04-03 21:41:46
0
2
666

要找出陣列的最大值,一個簡單的方法是

Math.max.apply(null, myArray)

但是,假設(shè)myArray 包含複數(shù),並且每個複數(shù)都有一個方法magnitude 來計算複數(shù)的長度,是否有一種簡單的方法可以找到myArray 中條目的最大值?我當(dāng)然可以做一個 loop 或一個函數(shù),但我的猜測是 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粉718730956
P粉718730956

全部回覆(2)
P粉846294303

本來打算提出同樣的建議,也給程式碼提供了一點現(xiàn)代語法,所以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粉306523969

您可以使用 Array#map 建立一個幅度陣列以套用 Math.max

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);
};
let b = [new Complex(1,2), new Complex(1,3),  new Complex(1,4)];
let res = Math.max(...b.map(x => x.magnitude()));
console.log(res);
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板