JavaScript to avoid pits

Source: Internet
Author: User

1, js arithmetic accuracy problem =

1 input >0.1+0.2==0.3 2 return >false 3 4 input >0.1+0.2 5 return >0.30000000000000004

Weapon: The idea is very simple, first assigned to a variable, with tofixed (reserved decimal place), function rounding, but this is not enough, if the value of processing also need to participate in the operation, you need to use number (value/variable);
1 input >var num=0.1+0.2;  2 input >var num2=num.tofixed (2);  3 input >num2 4 return > "0.30" 5 input >number (num2); 6 Back to >0.3

2,JS variable operation problem
1 Input > "2"-3 2 return >-1 3 4 input > "2" +3 5 return > "23" 6 7 Input > "2" +-3 8 return > "2-3"

Turn all the operation parameters first into number type and then the operation, if it is a variable type, you need to pay attention to whether your variable contains numbers, if not included is more troublesome, need to use isNaN (variable);
1 input >number ("2")-number ("3") 2 return >-1 3 4 input >number ("2") +number ("3") 5 return >5 6 7 input >number ("2") +-numb ER ("3") 8 return >-1

3, numeric string comparison size problem if the types of values on both sides are inconsistent, be sure to convert to a consistent type of variable comparison to be accurate (numeric and numeric string comparisons are also pits ...). )
1 input > "1" > "2" 2 return >false 3 4 input > "One" > "9" 5 return >false

JS in the true, false and undefined problem =
1 input >undefined==true 2 return >false 3 4 input >undefined==false 5 return >false 6 7 input >if (!undefined) Console.lo  g (false); 8 Back to >false


It looks more weird, right? , I want to say is: this no solution ... (Let me cry for a moment ...)
)。。。 For this can only be memorized, a simple summary is: undefined this east is not equal to false is not equal to true, but, but, knocking on the blackboard = in the judgment statement it is false








JavaScript to avoid pits

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.