behavior - JavaScript beginner: ParseInt() misunderstanding -


I have been teaching Javascript myself from a video that I have open around the Internet, and I talk to most things fast Many questions leave. So I check things in Firefox 21 through firebug 2.0.2 how they behave. This is the only purpose of the following code.

Console.log output

  & gt; & Gt; & Gt; Var n = parseInt ("34", "22", "18", 10); Console.log (n); 70  

My initial idea was that it parses every string supplied and then returns the amount. Then I did actual mathematics and realized that if the amount has been 74 in this case.

Even more interesting than this, and actually motivated me to do mathematics rather than my belief, to sum it out when I reduced the value of one of the numerical stars (22 in my experience 21 anyway) expected to return to 67 rather than 69.

Console.log Output

  In: 10 & gt; & Gt; & Gt; Var n = parseInt ("34", "21", "18", 10); Console.log (n); 67  

What is actually happening here? Is parseInt not designed just to accommodate many numerical strings?

No parseInt takes multiple strings; take it a string and an optional radix (i.e.

Please refer to the MDN reference

Your previous example is happening

  Paracent ("34", "21" , "18", 10)  

It is that you are saying javascript to parse 34 in base 21 (other parameters 18 and 10 are ignored) Base 21 In 34 67 (i.e. 3 x 21 + 4)

No. Adit: And based 22 34 70 (3 * 22 + 4). If you want to add numbers, you want to manually parse them first, then add them

or

 

code> var n1 = parseInt ( "34", 10); Var n2 = parseInt ("22", 10); Var n3 = parseInt ("18", 10); Var result = n1 + n2 + n3;

In addition, if you are positive that there are only numbers in strings (i.e. nothing like "22", "22 widgets"), parseInt parsed everything first to non-numeric characters ParseInt ("22 widgets") 22), then you can cheat a bit, and initially can put a +

or

  var n1 = + "34"; Var n2 = + "22"; Var n3 = + "18"; Var result = n1 + n2 + n3;  

The same result


Comments

Popular posts from this blog

Member with no value in F# -

java - Joda Time Interval Not returning what I expect -

c# - Showing a SelectedItem's Property -