【问题标题】:NaN issues on my sum of values in my array of objects我的对象数组中的值总和出现 NaN 问题
【发布时间】:2020-04-02 10:29:23
【问题描述】:

我一直在 VUE.js 中构建这个应用程序,但是在一个函数上有一个小问题,我试图在数组中添加每个对象的值..抛出一个 NaN 错误。让我们说

script

data(){
 return{
    array:[
      { product_name: "Chain Saw",
       product_free: 2,
       product_free_discount: 306.8,
       product_id: 1,
      }
      { product_name: "Ox",
       product_free: 1,
       product_free_discount: 60.8,
       product_id: 1,
      }
  ],
  totalDiscEquals:0,
 }
}

然后在我的计算属性上设置这个函数

COMPUTED
totalDiscObUnique() {
      let total = this.array.reduce(

        (a, b) => a + b.product_free_discount,
        0
      );
      console.log(total);

      return this.totalDiscEquals=total;
    },

像这样在创建的模块中创建进程

created(){
this.totalDiscObUnique;

但是当我在控制台记录 totalDisEquals 的值时,会抛出一个 NaN 结果,知道为什么会发生这种情况,或者为什么 NaN 经常出现?

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

new Vue({
  el: '#app',
  
  data: {
    array:[
      { 
        product_name: "Chain Saw",
        product_free: 2,
        product_free_discount: 306.8,
        product_id: 1,
      }, // <--- [1] missing comma here (,)
      { 
        product_name: "Ox",
        product_free: 1,
        product_free_discount: 60.8,
        product_id: 1,
      }
    ],
    totalDiscEquals:0,
  },
  
  /* [2] It's not recommended to assign new value to a data property
 in a computed, instead it intended to give you just a filtered / reduced
 / ... response.  */
  computed: {
    totalDiscObUnique() {
      return this.array.reduce((a, b) => a + b.product_free_discount, 0);
    },
  },
  
  created () {
    /* [3] also, there is no need to reassign the same value to a new
 data property again, instead you can use the computed itself wherever you
 want to use it */
    // this.totalDiscEquals = this.totalDiscObUnique
    console.log(this.totalDiscObUnique)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 {{ totalDiscObUnique }}
</div>

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多