javascript设置变量条件初始化

javascript设置变量条件初始化

问题描述:

简单的问题,但我被困...javascript设置变量条件初始化

我想设置初始化依赖于defaultQty plusmin。

所以是defaultQty = 1(如2的其它整数或3),则plusmin必须是1。

如果它不是一个整体整数(如0.5)的plusmin必须是0.1

define([ 
    'ko', 
    'uiComponent' 
], function (ko, Component) { 
    'use strict'; 

    return Component.extend({ 
     initialize: function() { 
      //initialize parent Component 
      this._super(); 
      this.qty = ko.observable(this.defaultQty); 
      this.plusmin = 0.1; 
     }, 

     decreaseQty: function() { 
      var newQty = this.qty() - this.plusmin; 
      if (newQty < this.defaultQty) { 
       newQty = this.defaultQty; 
      } 
      this.qty(newQty); 
     }, 

     increaseQty: function() { 
      var newQty = this.qty() + this.plusmin; 
      this.qty(newQty); 
     } 

    }); 
}); 
+0

this.plusmin =(this.qty == Math.floor(this.qty))? 1:0.1 – flowtron

this.plusmin = (this.defaultQty % 1 === 0) ? 1 : 0.1;

+0

是的!就是这个!在4分钟内我可以接受答案。但是当我以某种方式进入0.8时,输入字段中会出现0,7999999999999999。当数字不是整数时,是否有办法(有条件)将数字四舍五入为0,8? –

+0

不确定你在这里需要什么。 JavaScript以上述方式在数字精度上变得有趣,但它不应该影响这个问题的答案。如果这是一个全新的问题,那就把它作为一个新问题。 – andi

+0

已使用var newQty = Math.round((this.qty() - this.plusmin)* 100)/ 100;做这项工作:-) –

可以使用运算符(%),其分割后返回余:

(defaultQty % 1) > 0 ? plusmin = 0.1 : plusmin = 1;