2016-06-28 90 views
0

我使用的是空整數,並增加了一個以下列方式:增加一個可空整型值(INT?)

 item.addItem = function() { 
       //Check if item is already in the table on the right 
       if (viewModel.orderedItems.indexOf(this) < 0) { 

        if (isNaN(this.qty) || this.qty == 'undefined' || this.qty <= 0) { 
         //alert('is NaN1') 

         this.qty = 1; 
         //this.qty.value = 0; 
        } 
        //alert(this.qty.value); 
        viewModel.orderedItems.push(this); 
       } 
       else { 
        if (isNaN(this.qty) || this.qty == 'undefined' || this.qty <= 0) { 
         //alert('is NaN2') 
         this.qty + 1; 
         //this.qty.value = 0; 
        } 
        else { 
         viewModel.orderedItems.remove(this); 
         this.qty = this.qty + 1; 
         viewModel.orderedItems.push(this); 

        } 

       }` 

現在,這個數量顯示在inputfield,在那裏你可以改變它。假設我寫了15個數量,並決定'點擊'將其增加一個,結果爲'151'(15 +1),而不是16個。 我怎麼才能讓它實際上增加一個,而不是增加一個?

謝謝您的輸入。

+0

你可以施放類型'+ this.qty + 1'爲好,但不易閱讀! – ftor

回答

3

您可以將這個字符串嘗試使用parseInt以數量和其加1

parseInt(this.qty,10) + 1; 

,其中10爲基數

您還可以使用Number

旁邊有一個廣泛使用的構建正在使用Unary_plus試圖將其轉換爲數字。

所以你的情況這將是

+this.qty + 1; 
+0

這也適用,謝謝你的快速回復! – Paramone

+0

@ user2181397:你不需要爲這個例子指定基數,對吧?它會自動將其作爲小數檢測。 – niandrei

+0

@niandrei我個人不這麼認爲,但是我只是爲了安全而添加基數。 – Paramone

3

替換:

this.qty + 1; 

通過

parseInt(this.qty) + 1; 

但是你因爲什麼變化類型數量值的問題。

+0

Perfecto! (可以在10分鐘內接受) – Paramone