[Original] JavaScript Application tips

Source: Internet
Author: User

Some time ago, I collected and summarized the Application Techniques in Javascript, forming the following articles:Article:

    1. Javascript tips and tricks-1
    2. Javascript tips and tricks-2
    3. Javascript tips and tricks-3
    4. Javascript tips and tricks-4
    5. Javascript tips and tricks-5

Here I will describe these application skills in a centralized manner. If you think you have missed some useful application skills, please leave a message and I will update them to this Article in time.

  1. Convert to boolean type
    All values in javascript can be implicitly converted to the boolean type, for example:

     
    0 = false; // true 1 = true; // true ''= false // true null = false // true

    However, these values are not of the boolean type.
    Therefore, when we use three equal signs for comparison:

     
    0 = false; // false 1 = true; // false ''= false // false null = false // false

    The question now is how to convert other types to the Boolean Type:

     
    !! 0 = false; // true !! 1 = true; // true !! ''= False // true !! Null = false // true

    Note: The descriptions of null and false are incorrect as prompted by @ Zhao diandong @ kingwell. Null = false the result of this expression is false.
    According to the description in Javascript secret garden, only null and undefined in JavaScript are not objects, and all others are objects (including true and false ).

     1 "" = "0" //  False  2 0 = "" //  True  3 0 = "0"//  True  4   False = "False" //  False  5   False = "0" //  True  6   False = Undefined //  False  7   False = Null            //  False  8   Null = Undefined //  True  9 "\ T \ r \ n" = 0 //  True 

  2. assigning initial values to parameters
    JavaScript does not have the concept of overloading, but function parameters in JavaScript are optional, if less than one parameter is specified, the parameter is replaced by undefined .

     Function Plus (base, added) {return base + added;} Plus (2 ); // Nan 

    in this example, plus (2) and plus (2, undefined) is equivalent. The result of 2 + undefined is Nan .
    now, if the second parameter is not passed, how can we assign an initial value to it?

     Function Plus (base, added) {added = added | 1; return base + added;} Plus (2 ); // 3 plus (2, 2); // 4 

    some netizens mentioned that plus (2, 0) = 3; indeed, it seems that some special processing needs to be done here:

     Function Plus (base, added) {added = added | (added = 0? 0: 1); Return base + added ;}
  3. prevent others from loading your page in IFRAME
    If your website becomes very popular, there are many websites that want to link to your website, and even want to embed your webpage into its own Webpage Through IFRAME.
    This is not fun. How can this behavior be prevented?

     If (top! = Window) {top. location. href = Window. location. href ;}

    Code should be placed in head on each page, if you want to know that no one is using the Baidu blog, you will know.

  4. string replacement
    string. prototype. replace functions often confuse Programs who are very familiar with C # or Java.
    For example:

     'Hello world, hello world '. replace ('World', 'javascript '); // The result is "Hello JavaScript, the first parameter of the hello World "

    replace function is a regular expression.
    if you pass a string to the first parameter, only the matching string found in the first parameter is replaced.
    to solve this problem, we can use the regular expression:

     'Hello world, hello world '. replace (/World/g, 'javascript '); // The result is "Hello JavaScript, hello JavaScript "

    we can also specify case sensitivity when replacing:

     'Hello world, hello world '. replace (/Hello/GI, 'Hi'); // The result is "Hi world, hi world" 
  5. Convert arguments to an array
    Predefined variables in the functionArgumentsIt is not a real array, but an object similar to an array.

    It hasLengthAttribute, but there are no slice, push, sort and other functions, so how to makeArgumentsWhat about functions with these arrays?

    That is, how to makeArgumentsInto a real array?

    Function ARGs () {return []. Slice. Call (arguments, 0);} ARGs (2, 5, 8); // [2, 5, 8]
  6. Specify the second parameter for the parseint function.
    ParseintThe number used to convert a string to an integer. Syntax:
    Parseint (STR, [Radix])

    The second parameter is optional and used to specify the first parameter in hexadecimal notation.
    If the second parameter is not passed, follow the following rules:
    -> IfStrStarting with 0x, it is considered as hexadecimal.
    -> IfStrStarting with 0, it is considered to be in octal format.
    -> Otherwise, it is considered to be in decimal format.
    The following code will be confusing if you do not know the rules:

    Parseint ('08'); // 0 parseint ('08', 10); // 8

    Therefore, to ensure security, you mustParseintSpecify the second parameter.

  7. delete an element from the array
    maybe we can use Delete :

     var arr = [1, 2, 3, 4, 5]; Delete arr [1]; arr; // [1, undefined, 3, 4, 5] 

    , Delete does not really delete an element in the array. The deleted element is replaced by undefined , and the length of the array does not change.

    in fact, we can use array. the splice function in prototype deletes elements in the array, as shown in the following figure:

     var arr = [1, 2, 3, 4, 5]; arr. splice (1, 1); arr; // [1, 3, 4, 5] 
  8. the function is also an object
    in Javascript, the function is also an object, because we can add attributes to the function.
    For example:

     function add () {return add. count ++;} Add. count = 0; add (); // 0 add (); // 1 add (); // 2 

    we added the count attribute for the Add function, used to record the number of times this function is called.

    of course, this can be achieved in a more elegant way:

     function add () {If (! Arguments. callee. count) {arguments. callee. count = 0;} return arguments. callee. count ++;} Add (); // 0 add (); // 1 add (); // 2 

    arguments. callee points to the currently running function.

  9. maximum value in the array
    how to find the maximum value in an array of all numbers can be simply done through loops:

     var arr = [2, 3, 45, 12, 8]; var max = arr [0]; for (var I in ARR) {If (ARR [I]> MAX) {max = arr [I] ;}} Max; // 45 

    is there any other method? We all know that there is a math object in Javascript that processes numbers:

     math. max (2, 3, 45, 12, 8); // 45 

    then, we can find the maximum value in the array as follows:

     var arr = [2, 3, 45, 12, 8]; math. max. apply (null, arr); // 45 
  10. Add for IEConsole. LogFunction

    We often use firebug in Firefox.Console. LogTo record some information in the console.

    However, this method will block JavaScript Execution in IE (the same is true if firebug is not enabled in Firefox), because there is noConsoleObject exists.

    We can use the following tips to prevent such a situation:

    If (typeof (console) ==='undefined') {window. console ={ log: function (MSG) {alert (MSG) ;}}}console. log ('debug info. ');
  11. UndefinedIs it a reserved keyword in JavaScript?
    It looks like yes, but in fact undefined is not a keyword in javascript:

    VaR undefined = 'hello'; undefined; // 'hello'

    This code may surprise you, but it does work properly,UndefinedIt's just a predefined variable in JavaScript.
    Note: In javascript programs, do not do this. This technique only tells you the same thing.

  12. Determines whether a variable is undefined.
    In either case, a variable is undefined:

    1. variables are declared, but no value is assigned.

    VaR name; name = undefined; // true

    2. This variable has never been declared

    Name2 === undefined; // error-name2 is not defined

    In the second case, an error is thrown. If a variable is undefined and no error is generated?
    The following provides a general method:

    Typeof (name2) ==='undefined'; // true
  13. Preload Images

    Preload images are images that do not exist on the page, so that they can be quickly displayed using JavaScript later.

    For example, if you want to show another image when you move the mouse over an image:

     
    VaR IMG = new image (); IMG. src = "clock2.gif ";
     

    So how to load a group of images? Consider the following code:

     
    VaR source = require 'img1.gif ']; var IMG = new image (); For (VAR I = 0; I <source. length; I ++) {IMG. src = source [I];}

    In fact, this code can only pre-load the last image, because other images do not have time to pre-load when the loop comes.
    Therefore, the correct statement should be:

     
    VaR source = require 'img1.gif ']; for (VAR I = 0; I <source. length; I ++) {var IMG = new image (); IMG. src = source [I];}
  14. closure
    closure refers to the local variables in the function. When the function returns, this variable is still available.
    when you define another function inside the function, you create a closure, a famous example:
     function add (I) {return function () {return ++ I ;};} add (2 ). tostring (); // "function () {return ++ I;}" add (2 )(); // 3 

    Add (2) is a function, it may obtain the local variable I of the external function.
    reference

  15. private variable
    we often use naming conventions to indicate whether a variable is private (most commonly used ):

     var person = {_ name: '', getname: function () {return this. _ name | 'not defined' ;}}; person. getname (); // "not defined" 

    the underline prefix is used as a convention for private variables, but other developers can still call this private variable:

     person. _ name; // "" 

    how to create a real private variable in JavaScript?
    the main tips are to use the anonymous function and closure function ).

     var person = {}; (function () {VaR _ name = ''; person. getname = function () {return _ name | 'not defined' ;}}) (); person. getname (); // "not defined" typeof (person. _ name); // "undefined" 
  16. JavaScript does not have block-level context (scope)
    in Javascript, block-level code does not have context. In fact, only functions have their own context.

     for (VAR I = 0; I <2; I ++) {} I; // 2 

    if you want to create a context, you can use the self-executed anonymous function:

     (function () {for (VAR I = 0; I <2; I ++) {}}) (); typeof (I) === 'undefined'; // true 
  17. Weird Nan
    Nan is used to indicate that a value is not a number.
    Nan acts strangely in Javascript because Nan is not equal to any value (including itself ).

    Nan = Nan; // false

    The following code may drive some people crazy:

    Parseint ('hello', 10); // Nan parseint ('hello', 10) = Nan; // false parseint ('hello', 10) = Nan; // false

    So how to check whether a value is Nan?
    You can use window. isnan to determine:

    Isnan (parseint ('hello', 10); // true
  18. True and false values
    All values in javascript can be implicitly converted to the boolean type.
    In condition determination, the following values are automatically converted to false:
    Null, undefined, Nan, 0, '', false
    Therefore, the following complex judgment is not required:

    If (OBJ = undefined | OBJ = NULL ){}

    You only need to do this:

    If (! OBJ ){}
  19. modify arguments
    for example, add a value to arguments:

     function add () {arguments. push ('new value');} Add (); // error-arguments. push is not a function 

    . An error occurs because arguments is not a real array and there is no push method.
    solution:

     function add () {array. prototype. push. call (arguments, 'new value'); Return arguments;} Add () [0]; // "New Value" 
  20. Boolean and new Boolean
    we can regard boolean as a function to generate a Boolean value (literal ):

     Boolean (false) = false; // true Boolean ('') = false; // true 

    SO, Boolean (0) and !! 0 is equivalent.
    we can also regard boolean as a constructor and use New to create a Boolean object:

     new Boolean (false) = false; // false new Boolean (false) = false; // true typeof (new Boolean (false); // "object" typeof (Boolean (false); // "Boolean" 
  21. fast string connection
    we often use + to connect a short string to a long string, this is okay in most cases.
    however, if a large number of strings need to be connected, this method may cause performance problems, especially in IE.
     var starttime = new date (); var STR = ''; For (VAR I = 0; I <50000; I ++) {STR + = I;} alert (new date ()-starttime); // Firefox-18 ms, IE7-2060 Ms 
     var starttime = new date (); var arr = []; for (VAR I = 0; I <100000; I ++) {arr. push (I);} var STR = arr. join (""); alert (new date ()-starttime); // Firefox-38 ms, IE7-280 Ms 

    You Can See F Irefox seems to have optimized the + operator, while IE is dumb.

  22. unary operator +

    in Javascript, we can use the unary operator "+" before the string ". This will convert the string to a number. If the conversion fails, Nan is returned.

     2 + '1'; // "21" 2 + (+ '1 '); // 3 

    If + is used before a non-string, the conversion is attempted in the following order:

    1. call valueof ()
    2. call tostring ()
    3. convert to numbers
     + new date; // 1242616452016 + new date = new date (). gettime (); // true + new date () = Number (new date) // true 

    reference

  23. Encodeuri and encodeuricomponent
    The window. encodeuri function is used to encode a URL, but does not encode the following characters: ":", "/", ";", "?".

    Window. encodeuricomponent encodes the preceding characters.
    Here is an example:

    'Index. jsp? Page = '+ encodeuri ('/page/home. jsp '); // "index. jsp? Page =/page/home. jsp "'index. jsp? Page = '+ encodeuricomponent ('/page/home. jsp '); // "index. jsp? Page = % 2 fpage % 2fhome. jsp"

    Therefore, we often choose encodeuricomponent when encoding the URL.

  24. Table. innerhtml is a read-only attribute in IE.
    We often use Innerhtml Attribute to fill nodes, such:

     
    <Div id = "container1"> </div>
     
    Document. getelementbyid ('container1'). innerhtml = "Hello world! ";

    But set it in IETable. innerhtmlThis will cause an error:

    <Table id = "Table1"> </table>
     
    // Works well in Firefox, but fail to work in IE document. getelementbyid ('table1 '). innerhtml = "<tr> <TD> Hello </TD> <TD> world! </TD> </tr> ";

    In fact, the innerhtml attributes of table, thead, TR, select, and other elements are read-only in IE.

    If you create a table dynamically, the following provides a feasible method:

     
    <Div id = "Table1"> </div>
     
    Document. getelementbyid ('table1'). innerhtml = "<Table> <tr> <TD> Hello </TD> <TD> world! </TD> </tr> </table> ";
  25. 0.1 + 0.2! = 0.3
    JavaScript treats decimals as floating point numbers, so some rounding errors may occur, such:

     0.1 + 0.2; // 0.30000000000000004 

    you can use the tofixed method to specify the rounded decimal places:

     (0.1 + 0.2 ). tofixed (); // "0" (0.1 + 0.2 ). tofixed (1); // "0.3" 
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.