简体   繁体   中英

What is wrong in this code in js?

This code must give the output of the total cash , but rather gives wrong output? Can anybody please tell me what is wrong in it.

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

You need to parseInt your input values because they are strings and you'll only concat them that way. So, try:

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

See here: http://jsfiddle.net/3x9AH/

Your adding strings.

instead of:

this.total += itemCost;

try:

this.total += +itemCost;

You can try with:

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

You are attempting to add strings.

You should convert to a number, but be careful with arbitrary user input.

For example, none of the other answers will take into account the following inputs:

  1. "foo"
  2. "+Infinity"
  3. "-Infinity"

Change this line:

this.total += itemCost;

to:

this.total += itemCost >> 0;

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

this.total += parseFloat(itemCost);

The problem you have is that you are adding strings instead of numbers.

You can do something like this to fix it: this.total += Number(itemCost);

http://jsfiddle.net/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM