Use methods from apply
P粉718730956
P粉718730956 2024-04-03 21:41:46
0
2
296

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...

Here is a short code snippet that contains all the elements:

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

reply all(2)
P粉846294303

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粉306523969

You can use Array#map 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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!