Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js中的代码有什么错误?_Javascript - Fatal编程技术网

Javascript js中的代码有什么错误?

Javascript js中的代码有什么错误?,javascript,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 meth

此代码必须给出总现金的输出,但给出的输出是否错误? 谁能告诉我这里面有什么问题吗

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);
var收银机={
总数:0,
添加:功能(项目成本)
{
此项为总成本+=项目成本;
}
};
var i;
对于(i=0;i添加字符串

而不是:

this.total += itemCost;
尝试:

添加字符串

而不是:

this.total += itemCost;
尝试:


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

您可以执行以下操作来修复它:

此项。总计+=数量(项目成本);


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

您可以执行以下操作来修复它:

此项。总计+=数量(项目成本);


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

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

请参见此处:

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

this.total += parseInt(itemCost, 10);
请参见此处:

您可以尝试:

add: function(itemCost)
{
   this.total += parseInt(itemCost);
}
您可以尝试以下方法:

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

您正在尝试添加字符串

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

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

  • “福”
  • “+无限”
  • “-无限”
  • 更改此行:

    this.total += itemCost;
    
    致:


    您正在尝试添加字符串

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

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

  • “福”
  • “+无限”
  • “-无限”
  • 更改此行:

    this.total += itemCost;
    
    致:

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

    this.total += parseFloat(itemCost);
    
    使用
    parseFloat()
    函数,它用于解析字符串参数并返回浮点数

    this.total += parseFloat(itemCost);
    

    这将有助于显示实际输出与预期输出的对比。如果您实际查看实际输出,我认为您将得到一个非常好的提示;)这将有助于显示实际输出与预期输出的对比。如果你真的看了实际输出,我想你会得到一个很好的提示;)