2016-11-14 133 views
0

簡單的問題,但我被困...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

回答

3

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;做這項工作:-) –

0

可以使用運算符(%),其分割後返回餘:

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