Ten JavaScript skills per day (2) and javascript skills

Source: Internet
Author: User
Tags bitwise operators

Ten JavaScript skills per day (2) and javascript skills

1. Non-Numerical Conversion

UseNumber()Conversion:

  1. Undefined will be converted to NaN
  2. If the string starts with 0, the browser will ignore the leading 0 and will not convert it according to the octal
  3. If the string starts with 0x, the browser converts the string to decimal in hexadecimal format.
  4. If a string contains characters, all characters except (+,-,.) are converted to NaN. When the string contains any non-numeric characters, NaN is returned.
  5. If it is an object conversion, the object uses valueof () first, and then converts according to the rules. If there is no valueOf method, the toString method is called and then converted.

UseparseInt()Conversion:

  1. ParseInt ignores leading spaces until the first non-null character is parsed. If it is not a number or a positive or negative number, NaN is returned. If it is a number, it is parsed until the first non-number. Note: In parseInt, the decimal point is not a valid numeric character.
  2. ParseInt can recognize decimal, octal, and hexadecimal values. However, when parsing octal values, there are differences between ECMAScript 3 and ECMAScript 5. ECMAScript 3 will convert 070 to 56, however, ECMAScript 5 is converted to 70.
  3. Use the second parseInt Parameter
  4. Var num1 = parseInt ("10", 2); // 2 parse var num2 = parseInt ("10", 8) by binary ); // 8 parse var num3 = parseInt ("10", 10) by octal; // 10 parse var num4 = parseInt ("10", 16) by decimal ); // 16 Resolution in hexadecimal format

UseparseFloat()Conversion:

The first difference between parseFloat and parseInt is that it parses a string until it encounters an invalid floating point value character, which is more than parseInt.
0 is returned when the hexadecimal value is parsed.

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

The parseFloat function does not have the second parameter that can specify the base number. Therefore, only the decimal value is parsed.
If the string is an integer, return an integer instead of a floating point number.
var num = parseFloat("2.125e7");  //31250000

2. Use toString () to output different hexadecimal values.

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

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

3. Pay attention to NaN and Infinity when using bitwise operators.

When the bitwise operator is used for NaN and Infinity, both values are treated as 0. If a bitwise operator is used for a non-numeric value, the Number () function is used to convert the value to a numeric value.

Another thing to note is that the unsigned right shift of the negative number is to fill the blank space with the unsigned right shift of 0, instead of filling the blank space with the signed right shift, therefore, the unsigned right shift and the signed right shift of a positive number have the same result, but the negative number is different. The unsigned right shift operation regards the negative binary code as a positive binary code, and the negative number is expressed in the form of a supplementary code. Therefore, the result after the unsigned right shift is very different.

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

4. Special numeric operations

For numeric operations, if one of the operands is NaN, the result is NaN.
Apply the mona1 plus or minus operation (+,-, plus or minus sign) to a non-numeric value. If the value cannot be converted to a numeric value (Number () conversion), NaN is returned.

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

Infinity and 0 are multiplied by NaN, and non-zero values are multiplied by Infinity and-Infinity, depending on the plus and minus signs of the multiplier. Infinity and Infinity are multiplied by Infinity.

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

Zero division zero is NaN, and zero division zero is Infinity or-Infinity. Infinity divided by Infinity to NaN
For the modulo operation, the following equation is true:

Infinity % 2 = NaN; 2%-Infinity = 2; 0% Infinity = 0; // The result is 0 Infinity % 0 = NaN as long as the divisor is 0 and the divisor is not NaN; // The divisor can be any number. If the divisor is 0, the result is NaNInfinity % Infinity = NaN.

Addition operation: if both operands are strings, + becomes a string connection. If one is a string and the other is a numeric value, it is converted to a string and connected to the string. If one operand is an object, Boolean values call their valueOf method first, if none, call the toString method. Then, based on the return value type, determine whether to connect to the string or add the plus sign.

Infinity +-Infinity = NaN; var p = {valueOf: function () {return-1 ;}; var num = 1; var result = num + p; alert (result); // Add var p = {valueOf: function () {return "not a num" ;}}; var num = 1; var result = num + p; alert (result); // 1not a num string connection

Subtraction: subtraction is very similar to addition, and object processing is the same.

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

5. Use of Relational operators

Relational operators are less than (<), greater than (>), less than or equal to (<=), and greater than or equal to (> =)

If there is a value, a numerical comparison is executed. If the other value is not a value, it is converted to a value. The object uses valueOf and toString. In fact, no matter what operation is performed on the object, if valueOf exists, valueOf will be used to return the value; otherwise, toString will be used to return the value.
If both are strings, the character encoding value (ASCII value) of the string is compared)
Note that when a string is a numeric value at a time, when the string cannot be converted to a numeric value, that is, when NaN is the following:

Var result = "a" <3; // false a is converted to NaNvar result = "a"> = 3; // false. The value of any number is false compared with that of NaN.

6. = and =

In JavaScript, if the equations have different types or contain only one object, the comparison can be divided into two types: comparison after transformation and direct comparison without transformation. = Is converted to Comparison first, = is a direct comparison without conversion. For =, false is returned as long as the types are not equal. For =, there are several situations:

True is converted to 1, and false is converted to 0.
When comparing a string with a value, the string is converted to a value.
If there is only one object on both sides of the equation, this object will call valueOf to obtain the basic type. For example, if there is no valueOf method, the toString method will be called. If both sides are objects, no transformation is required.

Var p = {"name": "a"}; var q = {"name": "a"} var o = p; alert (q = p ); // false p and q point to different object addresses, although the object content is the same alert (o = p); // true

The following are special comparisons:

null == undefined  //trueNaN != NaN     //trueNaN == NaN     //false"NaN" == NaN    //falseundefined == 0   //falsenull == 0      //false

7. for-in statement

The output sequence of the for-in statement is unpredictable. The order may vary depending on the browser.
When the variable to be iterated is not null or undefined, no error is thrown in ECMAScript 5 but the loop body is not executed. If you want forward compatibility, It is not null or undefined before the loop.

8. swithc statement

The switch can use any data type.
Case values can be constants, variables, and expressions.
The switch statement uses the full comparison operator (=) when comparing values ).

var num = 25;switch (true) { case num<0:  alert("less 0");  break; case num>=0:  alert("more than 0");  break; default:  alert("error");}

9. Use of functions

If there is no return statement in the function or return does not contain any return value, the function will return undefined.
When the function is defined and called, the parameters are not consistent. In other words, there is no connection between the two parameters (Form parameters and real parameters. The variables provided during function definition are only convenient for use. Even if they are not defined, the parameters passed to the function can be obtained (through arguments []).

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

The relationship between the form parameter and arguments [] is as follows. Note the difference between the strict mode and the non-strict mode.

function howManyArgs(ss){ arguments[0]="test"; arguments[1]="test2" alert(arguments[0]);  //test alert(arguments[1]);  //test2 alert(ss);       //test}howManyArgs("a");function howManyArgs(ss){"use strict"arguments[0]="test";arguments[1]="test2"alert(arguments[0]);   //testalert(arguments[1]);   //test2alert(ss);        //a}howManyArgs("a");

10. Use of function parameters

When defining a function, we will write the parameters used into the brackets of the function, but it is not flexible if there are multiple optional parameters, in this case, you can use an object to encapsulate multiple optional parameters.

 function displayInfo(args){  var output = "";  if (typeof args.name == "string"){   output += "Name: " + args.name + "\n";  }  if(typeof args.age == "number"){   output += "Age: "args.age + "\n";  }  alert(output); } displayInfo({  name: "Nicholas",  age: 29 }); displayInfo({  name: "Greg" });

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.