To find the maximum value of an array, a simple way is
Math.max.apply(null, myArray)
However, assuming myArray
contains complex numbers, and each complex number has a method magnitude
to calculate the length of the complex number, is there an easy way to find myArray# Maximum value of entries in ##? I could of course make a
loop or a function, but my guess is that javascript has a good one line solution...
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粉8462943032024-04-04 11:41:14
Originally intended to suggest the same thing, but also give the code a bit of modern syntax, so Unmitigated beat me to it, but it works using 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
Yes, you can use extension syntax instead of apply, brackets instead of new Array, and you can use class syntax, since Complex is actually a class. < /p>
P粉3065239692024-04-04 10:33:44
You can use Array#map
< /a> to create an array of magnitudes to which Math.max
is applied.
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);