这个代码在js中有什么问题?

时间:2014-01-26 11:46:39

标签: javascript

此代码必须提供总现金的输出,而是提供错误的输出? 任何人都可以告诉我它有什么问题。

var cashRegister = {
   total:0,
   add: function(itemCost)
   {
      this.total += itemCost;
   }
};

var i;

for (i=0; i<4; i++)
{
   var a = prompt("Cost");
   cashRegister.add(a);
}
//call the add method for our items


//Show the total bill
console.log('Your bill is '+cashRegister.total);

6 个答案:

答案 0 :(得分:3)

您需要解析输入值,因为它们是字符串,您只能以这种方式连接它们。所以,试试:

this.total += parseInt(itemCost, 10);

见这里:http://jsfiddle.net/3x9AH/

答案 1 :(得分:2)

添加字符串。

而不是:

this.total += itemCost;

尝试:

this.total += +itemCost;

答案 2 :(得分:0)

您可以尝试:

add: function(itemCost)
{
   this.total += parseInt(itemCost);
}

答案 3 :(得分:0)

您正在尝试添加字符串。

您应该转换为数字,但要小心任意用户输入。

例如,其他答案都不会考虑以下输入:

  1. “foo” 的
  2. “+无限”
  3. “ - 无限”
  4. 更改此行:

    this.total += itemCost;
    

    为:

    this.total += itemCost >> 0;
    

答案 4 :(得分:0)

使用parseFloat()函数,它用于解析字符串参数并返回浮点数。

this.total += parseFloat(itemCost);

答案 5 :(得分:-1)

您遇到的问题是您要添加字符串而不是数字。

您可以执行以下操作来解决此问题: this.total += Number(itemCost);

http://jsfiddle.net/