Ten JavaScript tips per day of 2

  • 2021-06-29 10:01:26
  • OfStack

1. Conversion from non-numeric type to numeric value

Use Number() When converting:

undefined to NaN If the string starts with 0, the browser ignores the leading 0 and does not convert to octal If the string starts with 0x, the browser returns by converting 106 to 10 If a string has a character, it is converted to NaN except (+, -,.) and returns NaN if the string contains any non-numeric characters in the 106th digit If it is an object conversion, the object is first converted using valueof(), then converted according to the rules.If there is no valueOf method, the toString method is called and converted.

Use parseInt() When converting:

parseInt ignores leading spaces until the first non-empty character starts parsing and returns NaN if it is a non-number or a plus or minus sign.If it is a number, 1 will resolve to the first non-number.Note: Decimal points in parseInt are not valid numeric characters parseInt recognizes decimal, octal, and 106, but there are differences between ECMAScript 3 and ECMAScript 5 when resolving octal. ECMAScript 3 converts 070 to 56, but ECMAScript 5 converts to 70. Using the second parameter of parseInt

var num1 = parseInt("10",2);    //2  Press 2 Binary Parsing 
var num2 = parseInt("10",8);    //8  Press 8 Binary Parsing 
var num3 = parseInt("10",10);   //10  Press 10 Binary Parsing 
var num4 = parseInt("10",16);   //16  Press 106 Binary Parsing 

Use parseFloat() When converting:

The first difference between parseFloat and parseInt is that it is much larger than parseInt until an invalid floating-point numeric character is encountered in parsing the string.
Returns 0 when parsing a 106-digit value


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10

The parseFloat function does not have the second parameter to specify a cardinality, so it only parses the 10-digit value.
Returns an integer instead of a floating point number if the string is an integer
var num = parseFloat("2.125e7");  //31250000

2. Use toString() to output values in different binaries

This applies to integers. We can use toString() to return any binary integer.


var num = 10;
alert(num.toString());  //"10"
alert(num.toString(9));  //"11"
alert(num.toString(16));  //"a"

3. Note NaN and Infinity when using bit operators

When using bit operators with NaN and Infinity, both values are treated as 0.If a bitwise operator is applied to a non-numeric value, the value is first converted to a numeric value using the Number() function.

One more thing to note is that negative numbers are shifted unsigned to the right, unsigned to the right is to fill the space with 0, not like signed to the right, so the result is the same for positive numbers but different for negative numbers.The unsigned right-shift operation treats the negative binary code as the positive binary code, and the negative number is expressed as a complement, which results in very different results after the unsigned right-shift.


var oldValue = -64;            
var newValue = oldValue >>> 5

4. Special numerical operations

For numeric operations, if one operand is NaN, the result is NaN.
Use a unary plus or minus operation (+, -, plus or minus sign) for non-numeric applications and return NaN if the value cannot be converted to a numeric value (using Number ().


var s1 = "01", s2 = "1.1", s3 = "z", b = false,
o = {
valueOf: function(){
 return -1;
}
};
s1 = +s1;  //1   + Change to -:  -1
s2 = +s2;  //1.1       -1.1
s3 = +s3;  //NaN       NaN
b = +b;   //0        0
o = -o;  //-1        1

Infinity multiplied by 0 equals NaN, and non-zero multiplied by Infinity and -Infinity, depending on the sign of the multiplier.Multiplication of Infinity and Infinity equals Infinity.


var num1 =Infinity, num2 = 0, num3 = -2 ,num4 = -Infinity;
alert(num1 * num2);   //NaN
alert(num1 * num3);   //-Infinity
alert(num1 * num4);   //-Infinity

Zero divided by zero is NaN, non-zero divided by zero is Infinity or-Infinity.Infinity divided by Infinity is NaN
For modular operations, the following equation holds:


Infinity%2=NaN;
2%-Infinity=2;
0%Infinity=0;    // As long as the dividend is 0 , the divisor is not NaN And the results are 0
Infinity%0=NaN;   // The dividend can be any number, as long as the dividend is 0 And the results are NaN
Infinity%Infinity=NaN

Addition: If both operands are strings, +becomes a string connection.If one is a string and one is a numeric value, the numeric value is converted to a string, and then the string is connected. If one operand is an object, the Boolean value calls their valueOf method first, and if none, the toString method is called.Then, depending on the type of return value, determine whether the + sign should connect strings or add together.


Infinity + -Infinity = NaN ; 

var p = {
  valueOf: function () {
    return -1;
  }
};
var num =1;
var result = num +p;
alert(result);          // 0  Addition 

var p = {
  valueOf: function () {
    return "not a num";
  }
};
var num =1;
var result = num +p;
alert(result);        //1not a num  String Connection 

Subtraction operation: The subtraction operation and the addition operation have 10 points similar, and the object processing is the same, so it is not explained anymore.


Infinity - Infinity = NaN;
-Infinity - -Infinity = NaN;

5. Use of relational operators

The relationship operator is less than ( < ), greater than ( > ), less than or equal to (< =) and greater than or equal to ( > =)

As long as there is one value, a numerical comparison is performed and the other is not a number, which is converted to a number.Objects are first valueOf, then toString.In fact, no matter what operation the object performs, if there is valueOf, the value will be returned by valueOf, otherwise the value will be returned by toString.
If both are strings, compare the string's character-coded value (ASCII value)
As for the first, note that when a string 1 is a numeric value at one time and the string cannot be converted to a numeric value, NaN will see the following


var result = "a" < 3;  //false a Convert to NaN
var result = "a" >= 3;  //false  Any number and NaN All comparisons are false

6. ==and===

In JavaScript, if the two sides of the equation are of different types or contain only one object, the comparison can be divided into two situations: post-transition comparison and non-transition comparison. ==Converts first in comparison, ===is a direct comparison without conversion.For example===, return false as long as the types are not equal.For==there are several cases:

true converts to 1, false converts to 0.
Strings are converted to numbers when compared to numbers.
If there is only one object on either side of the equation, this object calls valueOf to get the basic type, such as the toString method without the valueOf method.Don't transition if you have both sides of the object.


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10
0

Here is a special comparison


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10
1

7. for-in statement

The output order of the for-in statement is unpredictable and may vary from browser to browser.
When the variable to iterate over is not null or undefined, an error is no longer thrown under ECMAScript 5 and the loop body is not executed.If forward compatibility is desired, it is determined not to be null or undefined before looping.

8. swithc statement

switch can use any data type.
case values can be constants, variables, and expressions.
The switch statement compares values using the equal comparison operator (===).


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10
2

Use of the 9 function

If there is no return statement in the function or if return has no return value, the function will return undefined.
A function is defined with no more than 1 argument when called.In other words, there is no relationship between the two parameters (formal and actual).The variables provided when defining a function are only convenient to use, and parameters passed to the function (via arguments[]) can be obtained without defining them.


function howManyArgs(){
 alert(arguments.length);
}
howManyArgs("a");     // 1
howManyArgs("a","b");   // 2
howManyArgs();      // 0

The relationships between the formal parameters and arguments[] are as follows, paying attention to the differences between strict and non-strict modes.


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10
4

10. Use of function parameters

When defining a function, the parameters used are enclosed in parentheses of the function, but when there are multiple optional parameters, it is not flexible enough to encapsulate multiple optional parameters using an object.


var num = parseFloat("0xA");  //0
var num = parseInt("0xA");   //10
5


Related articles: