Vue JS - Calculator - read output string as value

2019-08-23 04:18发布

问题:

I'm building a calculator to test out my Vue JS skills. I have the fundamentals working or at least set-up, however if I enter more than one number (e.g. 34) I can't get it to read all numbers (e.g. 34) as a whole value; rather it adds 3 and 4 to the total. The snippet I'm having trouble with is here:

press: function(num) {
  if(this.currentNum == 0) 
    {
      this.currentNum = num;
      this.output = num.toString();
    }
  else {
      this.output += num.toString();
      this.currentNum = this.output.parseInt();
    }
},

Here's the whole thing on CodePen for better context - https://codepen.io/ajm90UK/pen/BZgZvV

I think this is more of a JS issue rather than anything specific to Vue but even with parseInt() on the string I'm having no luck. Any suggestions on how I can read the display (output) would be greatly appreciated, I've been at this for hours now!

回答1:

parseInt() is not a method of the String prototype but rather a built-in function.

Update this line:

this.currentNum = this.output.parseInt();

to this:

this.currentNum = parseInt(this.output);

And it is a good idea to specify the radix in the second parameter - perhaps 10 in most all cases, for decimal numbers:

this.currentNum = parseInt(this.output, 10);

That way, if a value like 022 is entered, it isn't interpreted as the octal value (I.e. Decimal number 18).