How to force JS to do math instead of putting two

2018-12-31 10:05发布

I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?

var dots = 5
function increase(){
    dots = dots + 5;
}

Outputs: 55

How can I force it to output 10?

Could it possibly be an error in my script somewhere?

I'm initializing dots like this:

dots = document.getElementById("txt").value;

8条回答
不再属于我。
2楼-- · 2018-12-31 10:37

the simplest:

dots = dots*1+5;

the dots will be converted to number.

查看更多
人气声优
3楼-- · 2018-12-31 10:42

You have the line

dots = document.getElementById("txt").value;

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value);
查看更多
余生无你
4楼-- · 2018-12-31 10:48

DON'T FORGET - Use parseFloat(); if your dealing with decimals.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 10:48

This also works for you:

dots -= -5;
查看更多
宁负流年不负卿
6楼-- · 2018-12-31 10:52

parseInt() should do the trick

var number = "25";
var sum = parseInt(number) + 10;
var pin = number + 10;

Gives you

sum == 35
pin == "2510"

http://www.w3schools.com/jsref/jsref_parseint.asp

查看更多
不流泪的眼
7楼-- · 2018-12-31 10:56

UPDATED since this was last downvoted....

I only saw the portion

var dots = 5
function increase(){
    dots = dots+5;
}

before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.

One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:

<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>

where the event would give an error and clear the last character if the value is not a number:

<script type="text/javascript">
    function GetChar (event){
        var keyCode = ('which' in event) ? event.which : event.keyCode;
        var yourChar = String.fromCharCode();
        if (yourChar != "0" &&
            yourChar != "1" &&
            yourChar != "2" &&
            yourChar != "3" && 
            yourChar != "4" &&
            yourChar != "5" &&
            yourChar != "6" && 
            yourChar != "7" &&
            yourChar != "8" && 
            yourChar != "9")
        {
            alert ('The character was not a number');
            var source = event.target || event.srcElement;
            source.value = source.value.substring(0,source.value-2);
        }
    }
</script>

Obviously you could do that with regex, too, but I took the lazy way out.

Since then you would know that only numbers could be in the box, you should be able to just use eval():

dots = eval(dots) + 5;
查看更多
登录 后发表回答