首页 > 解决方案 > Javascript 对象值变量

问题描述

我想在 js 对象中进行一些计算。这可能吗?

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

process密钥应从和value计算target。有没有办法做到这一点?js

标签: javascriptobjectcalculation

解决方案


你可以做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

推荐阅读