자바 스크립트 개체 값 변수 [중복]

Nov 20 2020

js-object 내부에서 계산을하고 싶습니다. 이것이 가능한가?

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

process키를 계산해야 value하고 target. 이것에 대한 방법이 있습니까? js

답변

1 elclanrs Nov 20 2020 at 02:56

process게터 를 만들 수 있습니다 .

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;
    }
  }
];

그런 다음 속성 액세스를 사용합니다.

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

프로세스는 함수 또는 접근 자 여야합니다.

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