Javascript converts string to int when passed as function parameter

Asked

Viewed 76 times

1

I have the following excerpt:

"onclick=relatorio("+dados[i].cnpj+")"

data[i]. cnpj is a String type variable, or at least need it to be so, but Javascript converts the function parameter into a type number logo:

function relatorio(cnpj) {
     console.log(cnpj);
}

problem: when I need to make an ajax for the bank, the values differ
question: What could you do to ensure that data[i]. cnpj continued with the string type?

Resultado de console.log

I do not have permission from the client to disclose Cnpjs so it was censored even, but as you can see there the zero left was concatenated when the data type was changed

  • In addition to Wallace’s response, you can also use the cnpj.toString().

1 answer

4


It is because its concatenation makes the value passed as an integer in the expression.

That is, assuming the value of dados[i].cnpj be a string "1046", when mounting the expression "onclick=relatorio("+dados[i].cnpj+")" by means of concatenation, you are generating it:

onclick=relatorio(1046)

If you force the recognition as a string, it could solve the problem:

"onclick=relatorio('"+dados[i].cnpj+"')"

Quotation marks would cause the expression to be mounted like this:

  onclick=relatorio('1046')

In my opinion, the idea would be that you avoid these crazy concatenations, that are often very confusing.

You could store it in an attribute data-cnpj for example and retrieve it

"<button data-cnpj='" + dados[i].cnpj + "' onclick='relatorio(this.dataset.cnpj)'></button>"

The advantage of dataset is that usually, it always returns String.

<button onclick="console.log(this.dataset)" data-cnpj="0000000000111">
 Clica em mim!
</button>

  • 1

    Thanks, sometimes after hours programming I leave small details like this pass, but I’m grateful for the attribute tip, this makes the data clearer for future maintenance

  • @Leonardodasilva ok. I always try to go the way I will not get confused later, kkkkk. And yes, after hours of programming, instead of the bugle code, who we are.

Browser other questions tagged

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