增加一个可以为null的int(int?)的值

时间:2016-06-28 15:17:44

标签: javascript knockout.js integer nullable

我正在使用一个可以为空的整数,并按以下方式将其增加一个:

        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);

                    }

                }`

现在,此数据显示在输入字段中,您可以在其中进行更改。

让我们说,我写了15作为数量,并决定'点击'将其增加1,结果为'151'(15 +1),而不是16。 我怎么能让它实际增加一个,而不是添加一个?

感谢您的投入。

2 个答案:

答案 0 :(得分:3)

替换:

this.qty + 1;

通过

parseInt(this.qty) + 1;

但是你有一个问题,因为某些东西改变了数值的类型。

答案 1 :(得分:3)

您可以尝试使用parseInt将此字符串转换为数字,然后将1添加到

parseInt(this.qty,10) + 1;

其中10是基数

您也可以使用Number

除了广泛使用的构造之外,还使用Unary_plus来尝试将其转换为数字。

所以在你的情况下它将是

+this.qty + 1;