【问题标题】:How to avoid toFixed when the value is undefined or delayed response to that value当值未定义或延迟响应该值时如何避免 toFixed
【发布时间】:2019-05-06 12:17:58
【问题描述】:

我在控制台中看到此错误:

isNaN(...).toFixed 不是函数

这是我用 Vue.js 编写的一些 HTML 代码:

<v-flex xs3 class="text-lg-right" 
    v-for="(mrp, index) in [medicine.orderedMedView.combinations[combinationIndex]]" :key="index">
    <div class="primary-header-font">
        &#8377; {{ isNaN((mrp && (mrp.totalPrice - (mrp.totalPrice * (medicine.discountPercentage / 100))))).toFixed(2) ?
        0 :  
        (( mrp && mrp.totalPrice - (mrp.totalPrice * (medicine.discountPercentage / 100)))).toFixed(2) || 0 }} &nbsp;
    </div>
    <span v-if="mrp && mrp.totalPrice != NaN" class="secondary-header-font">
        {{ medicine.discountPercentage }}% 
    </span>
    <span v-if="mrp && mrp.totalPrice != NaN" class="secondary-header-font strike-through">
        &#8377; {{ mrp && mrp.totalPrice && (mrp.totalPrice).toFixed(2) || 0 }} &nbsp;
    </span>
</v-flex>

我猜在我的药物状态下,当我使用它时,响应会延迟......所以也许这就是它说“不是功能”的原因。我该如何解决这个问题?

【问题讨论】:

    标签: javascript vue.js vuejs2 tofixed


    【解决方案1】:

    isNaN 是一个检查提供的值是否为数字的函数。 它的返回值为truefalse。 因此,不能对isNaN的返回值使用函数toFixed

    尝试重新排列括号,使toFixed 位于数字之后。

    【讨论】:

    • 我已重新安排并解决了我的问题,无论如何感谢您的解决方案
    • 没问题。您能否为答案投票或给它绿色✅?让其他人看到。
    【解决方案2】:

    在执行 toFixed 之前检查变量是 isNaN。像下面的示例 sn-p

    var a=10.898978
    console.log(!isNaN(a)?a.toFixed(2):0)

    【讨论】:

      【解决方案3】:

      在 vue 中,你更愿意为这种语句使用方法。

      我想这是您在第一个三元表达式中错过toFixed(2) 的一个原因。

      所以在方法中你可以想象如下:

      price(mrp) {
         let price = mrp && (mrp.totalPrice - (mrp.totalPrice * (this.medicine.discountPercentage / 100));
         return isNaN(price) ? 0 : price;
      }
      

      在你的模板中:

      <v-flex xs3 class="text-lg-right" 
          v-for="(mrp, index) in [medicine.orderedMedView.combinations[combinationIndex]]" :key="index">
          <div class="primary-header-font">
              &#8377; {{ price(mrp) }} &nbsp;
          </div>
          <span v-if="mrp && mrp.totalPrice != NaN" class="secondary-header-font">
              {{ medicine.discountPercentage }}% 
          </span>
          <span v-if="mrp && mrp.totalPrice != NaN" class="secondary-header-font strike-through">
              &#8377; {{ mrp && mrp.totalPrice && (mrp.totalPrice).toFixed(2) || 0 }} &nbsp;
          </span>
      </v-flex>
      

      如果您想避免一些检查,您始终可以在v-flex 上使用v-if="medicine",因此在填充药物之前不会计算任何值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-03
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多