Zmienna wartości obiektu JavaScript [duplikat]

Nov 20 2020

Chcę wykonać obliczenia wewnątrz obiektu js. czy to możliwe?

foo: [
{
 value: 1000
 target:50
 process: (target*value)/100
},
{
 value: 500
 target:100
 process: (target*value)/100
}]

processKlucz powinien być liczony od valuei target. Czy jest na to sposób? Js

Odpowiedzi

1 elclanrs Nov 20 2020 at 02:56

Możesz zrobić processgetter:

const foo = [
  {
    value: 1000,
    target: 50,
    get process() {
      return (this.target * this.value) / 100;
    }
  },
  {
    value: 500,
    target: 100,
    get process() {
      return (this.target * this.value) / 100;
    }
  }
];

A następnie użyj dostępu do właściwości:

console.log(foo[0].process); //=> 500
console.log(foo[1].process); //=> 500
IsraGab Nov 20 2020 at 02:58

Proces powinien być funkcją lub akcesorium:

var foo= [
    {
     value: 1000,
     target:50,
     process() { return (this.target*this.value)/100}
    },
    {
     value: 500,
     target:100,
     process() { return (this.target*this.value)/100}
    }]
    // use it like this:
    console.log(foo[0].process()); //=> 500
    console.log(foo[1].process()); //=> 500