🖥️FE🖥️
ParseInt , +("2341a")
들눈
2023. 12. 1. 13:28
Both `parseInt` and `+` can be used to convert a value to an integer in JavaScript, but there are some differences between them.
1. **`parseInt`:**
- It's a function specifically designed for parsing strings.
- It takes two parameters: the string to be converted, and an optional radix (base) that specifies the numeral system to be used (e.g., base 10 for decimal).
- If the string begins with "0x," it's interpreted as a hexadecimal number; otherwise, it's treated as a decimal number.
- It parses the string from left to right until it encounters a character that is not a valid numeral in the specified base.
Example:
```javascript
const parsedInt = parseInt("123", 10); // Output: 123
```
2. **`+` (Unary Plus Operator):**
- It's an operator that can be used for both numeric conversion and addition.
- When used as a unary operator, it attempts to convert its operand to a number.
- It's less explicit than `parseInt` and doesn't allow specifying a radix.
Example:
```javascript
const convertedNumber = +"123"; // Output: 123
```
In most cases, if you are converting a string to an integer in a decimal numeral system, both `parseInt` and `+` will work. However, if you want to be more explicit about the conversion or need to handle different bases, `parseInt` might be a better choice. Additionally, `parseInt` can handle strings that contain non-numeric characters better than `+`, which might result in `NaN` (Not a Number).
Yes, using `parseInt` on the string "123a" will result in `123`. Here's an example:
```javascript
const result = parseInt("123a", 10);
console.log(result); // Output: 123
```
In this example, `parseInt` parses the string "123a" until it encounters the non-numeric character 'a', and it stops parsing at that point. As a result, the numeric part "123" is successfully converted to an integer, and the final result is `123`. If the string doesn't start with a valid numeric representation, `parseInt` will return `NaN` (Not a Number).