Javascript converts string to int when passed as function parameter

1

I have the following excerpt:

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

data [i] .cnpj is a String variable, or at least it needs to be this way, however JavaScript converts the function parameter to a type number logo:

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

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

  

I am not allowed, the client to divulge CNPJs then it was censored even, but as you can see there the zero the left was concatenated when the data type was changed

    
asked by anonymous 25.10.2018 / 20:19

1 answer

4

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

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

onclick=relatorio(1046)

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

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

The quotation marks would make the expression set up like this:

  onclick=relatorio('1046')

In my opinion, the idea is that you avoid those crazy concatenations , which often confuse a lot.

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

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

The advantage of dataset is that it usually returns String .

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