unary addition and unary subtraction in JS

Source: Internet
Author: User

Tag: The mode function will also script the parse addition operator ASC type

Most people are familiar with unary addition and unary subtraction, and their usage in ECMAScript is the same as what you learned in high school math.

Unary addition has no effect on numbers in nature:

1 var iNum =; 2 iNum = +iNum; 3 alert (iNum);    // output "+"

This code applies a unary addition to the number 20 and returns 20.

Although unary addition has no effect on numbers, it has an interesting effect on strings and converts strings into numbers.

1 var = "Snum"; 2 alert (typeof Snum);    // output "string" 3 var iNum = +snum; 4 alert (typeof INum);    // output "number"

This code converts the string "20" to a real number. When the unary addition operator operates on a string, it computes the string in a similar way to parseint (), except that the unary operator can convert it to a decimal value only if the string starts with "0x" (representing a hexadecimal number). Therefore, using a unary addition to convert "010", the resulting is always 10, and "0xB" will be converted to 11. (a string such as "7b" cannot be evaluated, returning Nan)

On the other hand, a unary subtraction is a negative value (for example, converting 20 to-20):

1 var iNum =; 2 iNum =-iNum; 3 alert (iNum);    // output " -20"

Similar to the unary addition operator, the unary subtraction operator also converts a string to an approximate number, which in turn is negatively valued. For example:

1 var = "Snum"; 2 alert (typeof Snum);    // output "string" 3 var iNum =-snum; 4 alert (iNum);        // output " -20" 5 alert (typeof INum);    // output "number"

In the preceding code, the unary subtraction operator converts the string "20" to 20 (the unary subtraction operator handles hexadecimal and decimal in a similar way to the unary addition operator, except that it also evaluates the value).

  

unary addition and unary subtraction in JS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.