Simple calculation between string and integer

Asked

Viewed 107 times

3

How to stop it from happening?

asd = "10"

novo=asd/2;

console.log(novo) // e ele me retorna 5

Whereas asd is a string and cannot be debt and treated as whole.

  • 3

    I think the only way is to check if it’s whole, and if it’s not, you don’t make the split.

  • The fact that this happens is basic javascript is not strongly typed

  • To understand the soul of Javascript you need to see WAT. After that, the perspective of the universe changes o_0

  • As Guilherme Bernal’s reply shows, Javascript was thought to allow this. What result you wanted to have? NaN?

2 answers

6


It is a feature of the language, Javascript is Weakly typed.

You can check the type of your variables is actually a number before proceeding, if you want:

if (typeof(asd) == "number")
    novo = asd / 2;
else
    throw "Tipo inválido";

More details about this check: How to know if a variable is of type Number in Javascript?

But this goes against the "spirit" of js. If you create a function that works with a numerical argument, a user can naturally expect that if he passes a string, it will work.

  • Interesting your code.. to be this throw ?

  • 1

    The throw looks like a return. It aborts the function with an error (may be a new Error()). The difference is that it does not return to who called the function, but to some level above that is waiting for an exception (catch). If there is nobody like this, everything is aborted and the browser shows the error in the console.

  • Detail: typeof is an operator and not a function, so parentheses are unnecessary - i.e., you could use if(typeof asd == "number").

  • @bfavaretto I put the parentheses for being in doubt about the precedence with the ==. Thank you.

2

You can always check if the variable is an integer number before dividing. I leave here a Jsfiddle with the example:

Jsfiddle

What I’m doing is:

1-I have a regular expression that defines integers

var verifyInt = /\d+/g; // Expressão regular

2- and with the match check whether it is whole or not

if (asd.match(verifyInt) != null)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.