【问题标题】:Javascript object value variable [duplicate]Javascript对象值变量[重复]
【发布时间】:2020-11-19 19:50:58
【问题描述】:

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

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

process 密钥应根据valuetarget 计算得出。有没有办法做到这一点?js

【问题讨论】:

标签: javascript object calculation


【解决方案1】:

您可以将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

【讨论】:

    【解决方案2】:

    进程应该是函数或访问器:

    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

    【讨论】:

      【解决方案3】:

      你不能这样做。 为什么不只是

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

      或者,如果您愿意,可以使用 Class 来解决这种情况:

      class Foo
      {
       constructor: (value, target) { 
          this.value = value;
          this.target = target;
          this.process = (target*value)/100;
       }
      }
      

      然后只是:

      foo: [
           new Foo(500, 100),
      new Foo(1000, 50)]
      

      【讨论】:

        【解决方案4】:

        您可以首先将“原始值”(valuetarget 属性)存储在一个数组中:

        const rawData = [{ value: 1000, target: 50 }, { value: 500, target: 100 }];
        

        然后map 在上面添加计算属性:

        const foo = rawData.map(({ value, target }) => ({ value, target, process: target * value / 100 }));
        

        【讨论】:

          【解决方案5】:

          假设对象是javascript,在对象之后添加一些计算。像这样:

          let foo = [{
           value: 1000,
           target:50,
           process:0
          },
          {
           value: 500,
           target:100,
           process:0
          }];
          foo[0]["process"] = foo[0]["target"] * foo[0]["value"];
          foo[1]["process"] = foo[1]["target"] * foo[1]["value"];
          console.log(foo[0]["process"]); // ==> 50000
          console.log(foo[1]["process"]); // ==> 50000
          

          【讨论】:

            猜你喜欢
            • 2012-09-21
            • 2011-08-29
            • 2015-12-31
            • 2017-07-05
            • 2021-01-01
            • 2012-11-28
            • 1970-01-01
            • 2017-07-01
            • 2011-12-11
            相关资源
            最近更新 更多