JavaScript Learning Skills _javascript Skills

Source: Internet
Author: User
Tags closure
  1. converts to Boolean type
    All values in JavaScript can be implicitly converted to a Boolean type, such as:
     0 = false;//True 
    1 = true;//true
    ' = = false/true
    NULL = = False//True
    But these values are not Boolean types.
    So when we compare using three equals numbers:
     0 = = false;//false 
    1 = = true;//false
    ' = = false//F Alse
    NULL = FALSE//False
    The question now is how to convert other types to Boolean types:
    !! 0 = = false; True 
    !! 1 = = true; True
    !! ' = = false//True
    !! NULL = = False//True

  2. To assign an initial value to a parameter
    There is no notion of overloading in JavaScript, but the parameters of a function in JavaScript are optional, and if you write a parameter less, it will be undefined Replaced.
     function plus (base, added) {
    return base + added;

    Plus (2);/NaN
    In this example, Plus (2) and plus (2, undefined) are equivalent, and the 2 + undefined result is NaN .
    The question now is, how do you assign an initial value if you don't pass the second argument?
     function plus (base, added) {
    added = added | | 1;
    return base + added;
    }
    Plus (2);//3
    Plus (2, 2);//4


    Some netizens refer to plus (2, 0) = 3; Yes, it seems this place has some special treatment to do:
     function plus (base, added) {
    added = added | | (added = = 0.0:1);
    return base + added;
    }

  3. prevents others from loading your page in an IFRAME
    If your site becomes very angry, there are a lot of websites that want to link to your site and even want to embed your Web page through an IFRAME.
    This is no fun, so how do you stop this behavior?
     if (top!== window) {
    Top.location.href = window.location.href;
    The code for
    should be placed in the head of each page, and if you want to know if there is anyone in the real world, look at Baidu's blog and you know it.

  4. The
  5. string substitution
    String.prototype.replace function often confuses programmers who are very familiar with C # or Java.
    For example:
     ' Hello World, Hello World '. Replace (' World ', ' JavaScript '); 
    The first parameter of the ' result ' hello JavaScript, Hello World '
    replace function is a regular expression.
    If you pass a string to the first argument, only the first matching string found is replaced.
    to solve this problem, we can use regular expressions:
     ' Hello World, Hello World '. Replace (/world/g, ' JavaScript '); 
    The result is "Hello JavaScript, hello JavaScript"
    We can also specify that the case be ignored when replacing:
     Hello World , Hello World '. Replace (/hello/gi, ' Hi '); 
    //The result is ' Hi World, Hi World '

  6. converting arguments into arrays
    The predefined variable arguments in a function is not a true array, but rather an array-like object.
    It has a length property, but there are no slice, push, sort functions, so how do you make arguments have functions that are available to these arrays?
    So how do you make arguments into a real array?
       function args () {
    return [].slice.call (arguments, 0);
    }
    Args (2, 5, 8); [2, 5, 8]

  7. Specify a second argument for the parseint function
    parseint The number used to convert a string to an integer, as follows:
       parseint (str, [radix])
    The second parameter is optional and is used to specify that the first parameter is binary.
    If the second argument is not passed, the following rule is followed:
    -> if str starts with 0x, it is considered to be 16.
    -> if str starts with 0, it is considered to be 8.
    -> Otherwise, think is 10 into system.
    So the following code will be confusing if you don't know the rules:
       parseint (' 08 '); 0
    parseint (' 08 ', 10); 8

    Therefore, be sure to specify a second parameter for parseint .
  8. to remove an element from an array
    Maybe we can do it through delete :
     var arr = [1, 2, 3, 4, 5]; 
    Delete Arr[1];
    Arr//[1, Undefined, 3, 4, 5]
    You can see that delete does not really delete an element in the array. The deleted elements are replaced with undefined , and the length of the array is unchanged.

    In fact, we can remove elements from an array by using the splice function in Array.prototype, as follows:
     var arr = [1, 2, 3, 4, 5]; Arr.splice (1, 1); 
    arr;//[1, 3, 4, 5]

  9. The
  10. function is also an object
    A function is also an object in JavaScript because we can add attributes to a function.
    For example:
     function Add () {
    return add.count++;
    }
    Add.count = 0;
    Add ();//0
    Add ();//1
    Add ();//2
    We added the Count property to the function add to record the times that this function was called Number.

    Of course this can be done in a more elegant way:
     function Add () {
    if (!arguments.callee.count) {
    Argumen Ts.callee.count = 0;
    }
    Return arguments.callee.count++

    Add ();//0
    Add ();//1
    Add ();//2
    Arguments.callee Point to the currently running function.

  11. The maximum value in the
  12. array
    How to find the maximum value in an array of all numbers, we can do it simply by looping:
     var arr = [2, 3,,, 8];
    var max = arr[0];
    for (var i in arr) {
    if (Arr[i] > max) {
    Max = arr[i];

    }
    Max;//
    is there another way? We all know that there is a Math object in JavaScript that handles numbers:
     Math.max (2, 3,,, 8);//
    then we can This finds the maximum value in the array:
     var arr = [2, 3, 8]; 
    Math.max.apply (null, arr);

  13. Add console.log function to IE
    Under Firefox and with the support of firebug, we often use console.log to record some information in the console.
    However, this approach prevents JavaScript execution under IE (as is the case with Firefox without Firebug), because no console object exists at this time.
    We can use the following tips to prevent this from happening:
       if (typeof (console) = = ' undefined ') {
    Window.console = {
    Log:function (msg) {
    Alert (msg);
    }
    };
    }
    Console.log (' Debug info. ');

  14. is undefined a reserved keyword in javascript?
    It looks like it, but in fact undefined is not a keyword in javascript:
       
    Undefined ' Hello '
    This code may make you feel strange, but it does work,undefined is just a predefined variable in JavaScript.
    Note: In JavaScript programs, do not do this, the trick is simply to tell you that there is such a thing.

  15. to determine whether a variable is undefined
    Two, one variable is undefined:
    1. The variable was declared, but there was no assignment
     var Name 
    Name = = undefined;//True
    2. This variable has never been declared
     name2 = = undefined;//Error–na ME2 is not defined 
    in the second case, an error is thrown, so if you judge whether a variable is undefined without creating an error?
    The following provides a common method:
     typeof (name2) = = ' undefined ';/true 

  16. preload pictures
    preload pictures are loads of pictures that do not exist on the page so that you can use JavaScript to quickly display them later.
    For example, you want to display another picture when you move the mouse over a picture:
     var img = new Image (); 
    Img.src = "Clock2.gif";
      onmouseover= "this.src=" Clo Ck2.gif '; ' 
    onmouseout= "This.src=clock.gif"/>

    So, how do you load a set of pictures? Consider the following code:
     var Source = [' img1.gif ', ' img2.gif ']; 
    var img = new Image ();
    for (var i = 0; i < source.length i++) {
    Img.src = source[i];
    }
    In fact, this code can only preload the last picture, because other pictures simply don't have time to preload when the loop arrives.
    So the correct wording should be:
     var Source = [' img1.gif ', ' img2.gif ']; 
    for (var i = 0; i < source.length i++) {
    var img = new Image ();
    Img.src = Source[i];
    }

  17. A
  18. closure (closure)
    closure refers to a local variable within a function that is still available when the function returns.
    When you define another function inside a function, you create a closure, a notable example:
     function Add (i) {
    return function () {
    return ++i;
    };
    }
    Add (2). toString ();//"function () {return ++i;}"
    Add (2) ();//3
    Add (2) is a function that may get the local variable i of the external function.
    reference article

  19. Private Variable
    We often use naming conventions to indicate whether a variable is a private variable (most commonly used to mark):
     var person = {
    _name: ' , the
    Getname:function () {
    Return This._name | | ' Not defined ';
    }
    }; The
    Person.getname ();//"Not defined"
    underscore prefix is used as a convention for private variables, but other developers can still call this private variable:
     per Son._name; 
    So, how do you create a real private variable in javascript? The
    main trick is to use anonymous functions (anonymous function) and closures (closure).
     var person = {}; 
    (function () {
    var _name = ';
    Person.getname = function () {
    Return _name | | ' Not defined ';
    }
    }) ();

    Person.getname ();//"Not Defined"
    typeof (Person._name);//"Undefined"

  20. JavaScript does not have block-level context (Scope)
    In JavaScript, block-level code has no context, and in fact only functions have their own context.
       


    I 2
    If you want to create a context, you can use a self executing anonymous function:
       


    }

    typeof (i) = = ' undefined '; True

  21. the Strange Nan
    Nan is used to indicate that a value is not a number.
    Nan behaves strangely in JavaScript because the Nan is not equal to any value (including itself).
       Nan = = nan; False
    Because the following code may cause some people to freak out:
       

    parseint (' Hello ', ten) = = NaN; False
    So how do you check to see if a value is Nan?
    You can use Window.isnan to determine:
       isNaN (parseint (' Hello ', 10)); True

  22. truth and False values
    All values in JavaScript can be implicitly converted to a Boolean type.
    In conditional judgments, the following values are automatically converted to false:
    null, undefined, NaN, 0, ', False
    Therefore, there is no need to make the following complex judgments:
       
    }
    And that's all you have to do:
       

    }

  23. Modify Arguments
    For example, add a value to the arguments:
       


    Add (); Error-arguments.push is not a function
    This can be an error because arguments is not a true array and there is no push method.
    Solution:
       



    Add () [0]; "New Value"

  24. Boolean and new Boolean
    We can think of Boolean as a function to produce a Boolean value (Literal):
     Boolean (') = = false;//True 
    So, Boolean (0) and !! 0 is equivalent.
    We can also think of Boolean as a constructor that creates a Boolean object by using new :
     new Boolean (false) = false; False 
    New Boolean (false) = = false;//True
    typeof (New Boolean (FALSE);//"Object"
    typeof ( false)); "Boolean"

  25. Quick string concatenation
    We often use + to concatenate shorter strings into a long string, which is not a problem in most cases.
    But if you have a large number of strings that need to be connected, this practice will run into performance problems, especially under IE.
     var starttime = new Date (); 
    var str = ';
    for (var i = 0; i < 50000; i++) {
    str + i;

    Alert (new Date ()-starttime);//firefox-18ms, ie7-2060ms
     var Starttim E = new Date (); 
    var arr = [];
    for (var i = 0; i < 100000; i++) {
    Arr.push (i);

    var str = arr.join ("");
    Alert (new Date ()-starttime);//firefox-38ms, ie7-280ms

    can see that Firefox seems to have optimized the + operator, and IE is a silly performance.
  26. unary operator +
    in JavaScript, we can use the unary operator "+" before the string. This converts the string to a number and returns Nan if the conversion fails.
     2 + ' 1 ';//' 2 + (+ ' 1 ');//3 
    If you use + in non-character String, an attempt is made to convert it in the following order:
    1. call valueof ()
    2. call ToString ()
    3. convert to number

    +new Date; 1242616452016
    +new Date = = new Date (). GetTime ();//True
    +new date () = = number (new Date)//True
    reference article

  27. The
  28. encodeURI and encodeURIComponent
    Window.encodeuri functions are used to encode a URL but do not encode the following characters: ":", "/", ";", "?". The
    Window.encodeuricomponent encodes the above characters.
    We illustrate by 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=%2fpage%2fhome.jsp "
    /pre> Therefore, we often choose encodeuricomponent when encoding URLs.

  29. table.innerhtml is a read-only property under IE
    We often populate nodes with the InnerHTML property of the node, such as:
     
     document.getElementById (' Container1 '). InnerHTML = "Hello world!"; 
    However, setting table.innerhtml under IE will result in an error:
    <table id= "table1" > </table> 
    //works with Firefox, but fail to work in IE 
    document.getElementById (' table1 '). Innerht ML = "<tr><td>Hello</td><td>World!</td></tr>";
    in effect, the innerHTML attributes of a table, THEAD, TR, select, and so on are read-only under IE.

    So if you create a table dynamically, here's a possible way to do it:
    <div id= "table1" > </div> 
     document.getElementById (' table1 '). InnerHTML = "<table><tr><td>hello</td ><td>World!</td></tr></table> "; 

  30. 0.1+0.2!= 0.3
    JavaScript treats decimals as floating-point numbers, so you may have some rounding errors, such as:
    0.1 + 0.2; 0.30000000000000004
    You can specify the number of decimal places rounded by the Tofixed method:
       (0.1 + 0.2). toFixed (); "0"
    (0.1 + 0.2). toFixed (1); "0.3"

JavaScript is a case-sensitive programming language.

To define an array:
var strweek= new Array (7);

Question-Mark expression
var i= (condition)? A:B;
Equivalent to the IF-ELSE statement; condition is established to execute a, does not establish execution B;

Switch statement

var i=3;
var result= "";
Swithck (i);
{
Case 1;
Result= "a";
Case 2;
result= "Second";
Case 3;
result= "Three";
Break
}

Date class
GetDate () getyear () Getmont ()
Getminutes () getHours () getseconds ()
SetTimeout ("Fution ()", 1000);
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.