Problems with adding keyboard support to JS calculator

前端 未结 1 970
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 23:49

I want to add keyboard support to my calculator. When i press operations with keyboard (i.e. +,-,* or /) js sees it as number, not as operation.

For example, when I com

1条回答
  •  自闭症患者
    2021-01-26 00:16

    Give this a shot. It's not got any functionality for delete key or arrow keys, but it will perhaps help move you forward more.

    
    
        
        
        
        
            

    An explanation of the code:

    The getValue routine does the bulk of fixing things up, and answers the key points in your original question:

    • If a variable is being interpreted as of type string it can mess up the computation. So you can convert a variable you don't know the type of to string by combining an empty string with the variable itself.

    • There is code to check for the existence of a decimal point, then use either parseFloat or Number to cast the type of the variable (parseInt is a more verbose alternative, needing radix of 10 - for a base 10 number).

    • A couple of other key variables are:

      • dp (decimal point). It stands for the number of digits past the decimal point, so any numbers you add after are divided by 10^dp (so 1 digit after dp is n * 1/10th, 2 digits is n * 1/100th etc).
      • nc (number of characters). Sometimes you can get odd rounding errors, so things like 1.111 suddenly become 1.111000000001 or something like that, so nc is used to count digits and decimal places entered and take the left number of characters based on nc.

    There is also some funky stuff going on, mimicking a normal calculator. So that when computation goes on, you can do something like enter:

    • 5 * = to give 25..
    • Press = again and it will give you 125.

    So the last number you enter becomes like a 'sticky' constant in memory. Whenever a new value gets entered, that becomes the new 'sticky' value. So:

    • 3 * 4 = (yields 12),
    • = then yields 48 etc.

    So: - the values array is used to store both the sticky value and the total:

    • It gets re-evaluated in performMaths()
    • adjusted in operator and = event handlers.
      • the boolean newValue is set to true whenever a number is pressed, and false whenever an operation, such as +, -, /, * or = is pressed.

    checkCalcKey() is an event handler for onkeydown upon the input HTML control's. By returning false, it prevents the character you type from build input. Instead it defers to the click handler of the corresponding button and any character entry into the input control value property gets performed via that handler instead. (More info here).

    0 讨论(0)
提交回复
热议问题