Using Javascript parseInt() and a Radix Parameter

2019-01-15 12:06发布

Can anyone explain how the parseInt() functions works and what the Radix Parameter is?

As a case study, I am trying to get to grips with this code snippet:

var maxChars = parseInt( formField.attr('maxlength') ? formField.attr('maxlength') : counter.text() );

Can you also explain how this code works? Why is formField.attr('maxlength') there twice? I find the use of operators here pretty darn confusing!

How does the Radix Parameter work in this example?

3条回答
我只想做你的唯一
2楼-- · 2019-01-15 12:36

The radix is another name for base, i.e. 2 for binary, 10 for decimal, 16 for hexadecimal, explained in more detail on the Mozilla Developer Network site.

In your example there is no radix parameter, so the interpreter will fall back to the default behaviour, which typically treats numbers as decimal, unless they start with a zero (octal) or 0x (hexadecimal).

查看更多
欢心
3楼-- · 2019-01-15 12:37

parseInt takes two parameters, the second one is optional. String and Radix.

String is the value to parse. If the value provided is not a string it will convert it to a string.

Radix is an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string.

In your code snippet the Radix isn't specified and is assumed to be default 16.

var maxChars = parseInt( formField.attr('maxlength') ? formField.attr('maxlength') : counter.text() );

You are defining a variable called "maxChars". This variable is equal to the evaluation of a short hand IF statement.

You are getting the attribute from the variable which is expected to be a selector "formField" called "maxLength". The value will return as a integer, it will fallback on it's default radix.

The IF statement checks if the returned value is true or false. 0, false, ectcetera would result in the value of the variable "maxChars" to be set to "counters" combined text. IF true it would result in the variable to be set as selector "formField" attribute called "maxLength".

formField.attr('maxlength')

Is there twice because one is used in an IF statement evaluation and the other is used as the value if the condition in the IF statement results as TRUE.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-15 12:53

In the ECMA Script 5 when the string starts with 0 and no radix is specified the default behavior is decimal (as opposed to the earlier versions in which it was octal)

Source: parseInt() on Mozilla Developer Network

查看更多
登录 后发表回答