Pour trouver la valeur maximale d'un tableau, un moyen simple est
Math.max.apply(null, myArray)
Cependant, en supposant myArray 包含复数,并且每个复数都有一个方法 magnitude 来计算复数的长度,是否有一种简单的方法可以找到 myArray 中条目的最大值?我当然可以做一个 loop ou une fonction, mais je suppose que javascript a une belle solution en une seule ligne...
Voici un court extrait de code avec tous les éléments :
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
J'allais suggérer la même chose, mais aussi donner au code un peu de syntaxe moderne, donc Unmitigated m'a devancé, mais cela fonctionne en utilisant 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 nowOui, vous pouvez utiliser la syntaxe d'extension au lieu de apply, des parenthèses au lieu de new Array, et vous pouvez utiliser la syntaxe de classe car Complex est en fait une classe.
Vous pouvez utiliser
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);