2016.3.23 _ JavaScript basics _ 3 _ 14th days

Source: Internet
Author: User

2016.3.23 _ JavaScript basics _ 3 _ 14th days

Recently, I caught a cold and got tired. At the same time, I also found that the quality of my article cannot be guaranteed by updating an article every day. Instead of writing some hydrology every day, it is better to calm down and sort out some knowledge before presenting it to everyone.

We are sorry to inform you that the update date of this series is changed from one day to three days from today ~ The actual time will only be shorter and will not be longer.

At the same time, I am very grateful to many of my friends for their long time. Thank you.

1. Timer

In our daily development, we often need to wait several seconds for a certain effect to trigger, which leads to what we want to learn today,Timer.

1.1 setTimeout ()

The setTimeout () method is used to call a function or computing expression after a specified number of milliseconds.

Tip: 1000 milliseconds = 1 second.

setTimeout(code,millisec,lang)

Parameters Description
Code Required. The JavaScript code string to be executed after the function to be called.
Millisec Required. The number of milliseconds to wait before executing the code.
Lang Optional. The script language can be JScript.
        

Click "Hello" in three seconds ".

Click me<Script> function myFunction () {setTimeout (function () {alert ("Hello")}, 3000) ;}</script>

CleanTimeout

    cleanTimeout(myFunction);
1.2 setInterval ()

The setInterval () method can call functions or computation expressions according to the specified period (in milliseconds.

The setInterval () method does not stop calling the function until clearInterval () is called or the window is closed.

The ID value returned by setInterval () can be used as a parameter of the clearInterval () method.

Tip: 1000 milliseconds = 1 second.

setInterval(code,millisec,lang)

Parameters Description
Code Required. The JavaScript code string to be executed after the function to be called.
Millisec Required. The number of milliseconds to wait before executing the code.
Lang Optional. The script language can be JScript.
    
<Script type = "text/javascript"> var int = self. setInterval ("clock ()", 1000); function clock () {var d = new Date (); var t = d. toLocaleTimeString (); document. getElementById ("clock "). value = t ;}</script>Stop

Clear Timer: clearInterval

    clearInterval(clock);
1.3 What is the difference between setTimeout and setInterval?

In the two modules above, we can see that all these two methods are timers, but we find that there are no differences between the two methods except the names. Why are there two more methods?

Because setTimeout (expression, delay time) is executed once after the specified delay time after loading. Remember, the number of times is once.

The setInterval (expression, interaction time) is different. It executes the expression at a specified time after loading.

So,They are completely different..

Many people are used to include setTimeout in the executed function, and then use setTimeout outside the function to implement scheduled execution.

In this way, the setTimeout outside the function triggers setTimeout again when executing the function to form a periodic Effect of recurrence.

Each has its own advantages. When using setInterval, You need to manually stop the tick trigger.

The setTimeout nested in the method can be stopped based on the internal logic of the method.

In fact, the two things can be simulated with each other. The specific use depends on the needs at that time.

Just as for can simulate all loops including branches, but also provides do and while.

2. type conversion

In JavaScript, type conversion is classified into forced conversion and implicit conversion.

2.1 forced conversion
Var a = "50"; // String var B = 10; // Number // String --> Number var a = Number (); // prompt Number alert (typeof a); // Number --> String var B = String (B); // prompt String alert (typeof B );

Supplement:

ParsetInt (): Extract an integer from left to right in a string. The end of a non-number is returned. (14 in 14.2312) parsetFloat (): extract the decimal Number () in the String: Convert the String to a Number String (): Convert the Number to a String 2.2 implicit conversion
// Implicit type conversion var a = "5"; // string type var B = 10; // digital type alert (a-B ); // implicit conversion converts string "5" to number 5
3. Functions

A function is an event-driven or reusable code block that is executed when it is called.

In other words, a function in computer programming language is a fixed piece of code that can complete certain functions.

3.1 How to define functions 3.1.1 famous functions (don't ask me what this is, I don't know, 23333)

A function is a block of code enclosed in curly braces. The keyword function is used before:

Function functionname () {the code to be executed here}

When this function is called, the code in the function is executed.

A function can be called directly when an event occurs (for example, when a user clicks a button), and JavaScript can call the function anywhere.

Tip: JavaScript is case sensitive. The keyword function must be in lower case and must be in the same case as the function name.

3.1.2 anonymous Functions
    var MR_LP = function(x){        if(x > 0){            return x;        }        else{            return -x;        }    };

We found that the above function does not have a specific function name, but it assigns the function to the variable MR_LP, so our MR_LP can call this function.

3.1.3 Summary

These two definitions are actually completely equivalent. You only need to note that the second method is based on the complete syntax. You need to add a ";". To end the assignment statement.

3.2 call a function with Parameters

When calling a function, you can pass values to it. These values are called parameters.

These parameters can be used in functions.

You can send any number of parameters separated by commas:

MyFunction (argument1, argument2) // when you declare a function, declare the parameter as a variable: function myFunction (var1, var2) {the code to be executed here}

The variables and parameters must appear in the same order. The first variable is the given value of the first passed parameter, and so on.

3.3 functions with return values

Sometimes, we want the function to return the value to the place where it is called.

You can use the return statement.

When the return statement is used, the function stops execution and returns the specified value.

    function myFunction()    {    var x=5;    return x;    }

The above function returns 5.

Note: The entire JavaScript operation will not stop. It is just a function. JavaScript will continue to execute the code from where the function is called.

3.4 how to call a function

To call a function, you only needFunction name + ParameterYou can complete the call. Note that when a function has parameters, you must input parameters in sequence.

Do you still remember the anonymous function just now? You can callMR_LPYou can directly call a function, for example:

MR_LP (100); // returns 100 MR_LP (-99); // returns 99, which is reversed in the function.

In addition, JavaScript allows the input of any parameter without affecting the call, so there is no problem with the incoming parameters than the defined parameters, although these parameters are not required inside the function.

MR_LP (100, '20140901'); // return 13115235 MR_LP (-99, 'asdasd', 'aqweqvx '); // return 99, which is reversed in the function

Of course, the number of input parameters is smaller than that defined.

MR_LP (); returns NaN

In this case, the function parameter is undefined and the calculation result is NaN (Not a Number ).

Therefore, in our daily development, we must pre-judge the parameters.

Var MR_LP = function (x) {// determine whether the parameter is of the Number type if (typeof x! = 'Number') {// throw an exception throw 'not a number';} if (x> 0) {return x ;}else {return-x ;}};
3.5 return

There is a mechanism for automatically adding semicolons at the end of a line in the JavaScript engine, but this mechanism may also make you stick to it. (Refer to the return project of Apple over the past few years)

    function lol(){        return{ name : 'lol'};    }    lol();  //{name : 'lol'}

However, if we divide the return statement into two sentences.

Function lol () {return; // The end of return is automatically added with a semicolon, equivalent to return undefined; {name: 'lol '}; // will never be executed}

Therefore, we can use this method when writing normally:

Function lol () {return {// The semicolon is not automatically added at this time, because {} indicates that the statement has not ended name: 'lol '};}
4. arguments

JavaScript also has a free keyword.argumentsIt only works within the function and always points to all parameters passed by the caller of the current function. Arguments is similar to Array, but it is not actually.

function foo(x){    alert(x);   //10    for(var i = 0 ; i < arguments.length ; i ++){        alert(arguments[i]);    //10 , 20 , 30    }}foo(10, 20, 30);

With arguments, you can obtain all parameters passed by the caller.

That is to say, the function does not define any parameters, and the parameter value can still be obtained.

    function MR_LP(){        if(arguments.length === 0 ){            return 0;        }        var x = arguments[0];        return x >= 0 ? x : -x;    }    MR_LP(0);       //0    MR_LP(100); //100    MR_LP(-99); //99

In fact, arguments is most commonly used to determine the number of input parameters. You may see the following statement:

// Foo (a, [B], c) // receives 2 ~ Three parameters. B is an optional parameter. if only two parameters are input, B is null by default. function foo (a, B, c) {if (arguments. length = 2) {// The actual obtained parameters are a and B, and c is undefined c = B; // assign B to c B = null; // change B to the default value }}

To change the intermediate parameter B to an "optional" parameter, you can only use arguments to determine the parameter, and then re-adjust the parameter and assign a value.

5. rest Parameters

Since JavaScript Functions allow receiving arbitrary parameters, we have to use arguments to obtain all parameters:

    function foo(a,b){        var i,rest = [];        if(arguments.length > 2){            for(i = 2; i < arguments.length; i++){                rest.push(arguments[i]);            }        }        console.log('a = ' + a);        console.log('b = ' + b);        console.log(rest);    }

To obtain parameters other than the defined parameters a and B, we have to use arguments and the loop starts from index 2 to exclude the first two parameters, is there a better way to get additional rest parameters?

The rest parameter introduced by ES6 can be rewritten:

Function foo (a, B... rest) {console. log ('a = '+ a); console. log ('B =' + B); sonsole. log (rest);} foo (1, 3, 4, 5); // result: // a = 1 // B = 2 // Array [3, 4, 5] foo (1); // result: // a = 1 // B = undefined // Array []

Rest parameters can only be written at the end....Identity. From the running results, we can see that the input parameters are first bound to a and B. Redundant parameters are handed over to the variable rest in the form of an array, so we can get all the parameters without arguments.

If the input parameters are not fully defined, the rest parameter will receive an empty array (Note: Not undefined ).

Because the rest parameter is the new ES6 standard, we need to pay attention to compatibility issues during use.

6. Variables and scopes

In JavaScript, variables declared with var are actually scoped.

If a variable is declared within your function body, the scope of the variable is the entire function body and cannot be used in vitro.

Function foo () {var x = 1; x = x + 1;} x = x + 2; // referrenceError! No more function reference variable x in Vitro

If two different functions declare the same variable, the variable takes effect only in the corresponding function.

In other words, variables of the same name in different functions are independent of each other and do not affect each other:

    function foo(){        var x = 1;        x = x + 1;    }    function bar(){        var x = 'A';        x = x + 'B';    }

Because JavaScript functions can be nested, internal functions can access variables defined by external functions, but they cannot.

Function foo () {var x = 1; function bar () {var y = x + 1; // bar can access the foo variable x! } Var z = y + 1; // ReferenceError! Foo cannot access the bar variable y! }

What if the variable names of the internal and external functions are the same?

    function foo(){        var x = 1;        function bar(){            var x = 'A';            alert(' x in bar() = ' + x);    //'A'        }        alert('x in foo() = ' + x); // 1        bar();    }

This shows that JavaScript Functions start from their function definitions when searching for variables, and start from "Inside" to "outside.

If the function name defined by the internal function has a variable with the same name as the external function, the variable of the internal function will "Block" the variable of the external function.

6.1 variable increase

The Function Definition of JavaScript has a feature. It first scans the statements in the entire function body and "promotes" all declared variables to the top of the function;

    function foo(){        var x = 'hello, ' + y;        alert(x);        var y = 'larra';    }    foo();

Statementvar x = 'hello' + y;No error is reported because the variableyIt will be declared later, but our alert will prompthello, undefined, Which indicates our VariablesyThe value is undefined.

This is because the JavaScript engine automatically promotes the declaration of variable y, but does not increase the value assignment of variable y.

Therefore, when defining variables in the function, strictly abideThe function first declares all variables.The most common principle is to use a var to declare all the variables used in the function.

Function foo () {var x = 1; // The initial value of x is 1 y = x + 1; // The initial value of y is 2 z, I; // z and I are undefined // other statements for (I = 0; I <100; I ++ ){...}}
6.2 global variables

Variables not defined in any function have a global scope.

In fact, JavaScript has a Global Object window (that is, the browser object) by default. The global scope variable is actually bound to an attribute of window:

    var course = 'learn JavaScript';    alert(course);    alert(window.course);

Therefore, direct access to the global variable course is exactly the same as access to window. course.

The function can be defined in two ways:var foo = function(){}The defined function is actually a global variable. Therefore, the definition of the top-level function is also considered as a global variable and bound to the window object:

'Use strict '; function foo () {alert ('foo');} foo (); // directly call foo (); window. foo (); // use window. foo () call

Therefore, we can make a bold guess that the alert () function we call each time should also be a variable of window.

Note:

JavaScript actually has a global scope. Any function (the function is also regarded as a variable). If it is not found in the current function scope, it will continue to look up the layer. If it is not found in the global, the error of ReferenceError is reported directly.

6.3 local variables

Since the scope of JavaScript variables is actually inside the function, we cannot define variables with local scopes in the for loop or other statement blocks.

Function foo () {for (var I = 0; I <100; I ++) {//} I + = 100; // variable I can still be referenced}

To solve the block-level scope, ES6 introduces new keywords.let, Replace var WITH let to declare a block-level element scope variable:

    function foo(){        var sum = 0;        for(let i = 0; i< 100 ; i++){            sum +=i;        }        i +=1;  //SyntaxError    }

A pitfall

        
I'm button 1 I'm button 2 I'm button 3 I'm button 46.4 Constants

The most obvious feature of a variable is that the stored values can be changed at will. constants are the opposite. Once a constant is determined, it cannot be changed.

var PI = 3.14;

After the ES6 standard is published, we can use the new keyword const to define constants. Both const and let have block-level scopes.

Const PI = 3.14; PI = 3; // Some browsers will not report errors, but there is no actual effect PI; // 3.14
7. Use the closure 7.1 function as the return value.

In addition to accepting a function as a parameter, a higher-order function can return the function as a returned result.

Let's implement a summation of Array. Generally, the summation function is defined as follows:

    function sum(arr){        return arr.reduce(function(x,y){            return x + y;        });    }    sum([1,2,3,4,5]);   //15

However, if you do not need to calculate the sum immediately, but in the code below, you can directly return the sum function as needed.

    function lazy_sum(arr){        var sum = function(){            return arr.reduce(function (x,y){                return x + y;            });        }        return sum;    }

When we calllazy_sum()The returned result is not a result of summation, but a function of summation:

var f = lazy_sum([1,2,3,4,5]); //function sum()

Call a functionfIs the result of calculating the sum, but the sum function:

f(); //15

In this example, we define the sum function in the lazy_sum function, and the internal function sum can reference the parameters and local variables of the external function lazy_sum. When lazy_sum returns the sum function, related Parameters and variables are stored in the returned function."Closure".

Note that when we call lazy_sum (), a new function is returned for each call, even if the same parameters are input.

    var f1 = lazy_sum([1,2,3,4,5]);    var f2 = lazy_sum([1,2,3,4,5]);    f1===f2;    //false

The call results of f1 () and f2 () do not affect each other.

Note that the returned function references the local variable arr within its definition. Therefore, when a function returns a function, its internal local variables are also referenced by the new function, closures are easy to use and are not easy to do.

In addition, you must note that the returned function is not executed immediately, but is executed only when f () is called. Let's look at another example:

    function count(){        var arr = [];        for(var i = 1; i<=3;i++){            arr.push(function(){                return i * i;            });        }        return arr;    }    var resullts = count();    var f1 = results[0];    var f2 = results[1];    var f3 = results[2];

In the preceding example, a new function is created for each loop, and the three functions are added to an array loop and returned.

You may think that the substitute f1 (), f2 (), f3 () results are, 9. But the actual situation is

    f1();   //16    f2();   //16    f3();   //16

All of them are 16, because the returned function references variable I, but it is not executed immediately. When all three functions are executed, the value of I has changed to 4, so all the results are 16.

Therefore, pay attention to the following points when returning the closure:Return functions do not reference any cyclic variables, or variables that will change in the future.

What if it is required in the program?

We need to re-create a function and bind the current value of the loop variable with the function parameters. Then we don't have to worry about how the loop variable will change, the parameter values bound to the function will not change.

    function count(){        var aarr = [];        for(var i=1;i<=3;i++){            arr.push((function(n){                return function(){                    return n*n;                }            })(i));        }        return arr;    }    var results = count();    var f1 = results[0];    var f2 = results[1];    var f3 = results[2];    f1();   //1    f2();   //4    f3();   //9

Note that in the above program, we created"Anonymous function and immediate execution".

    (function(x){        return x*x;    })(3)   

Theoretically, to create an anonymous function and execute it immediately, you can write it here:

function (x){return x * x;} (3);

However, JS Syntax Parsing will deem this function as incorrect and prompt SyntaxError. Therefore, we need to use parentheses to define the entire function:

(function(x){return x*x;})(3);

In our daily work, we will write this function separately.

    (function(x){        return x*x;    })(3);

So we have said that the closure function is very powerful. Where is it powerful?

In an object-oriented programming language, such as Java and C ++, to encapsulate a private variable in an object, you can use private to modify a member variable.

In languages without a class mechanism and functions, a private variable can also be encapsulated with closures. We use JavaScript to create a counter:

    function create_counter(initial){        var x = initial || 0;        return{            inc : function(){                x += 1;                return x;            }        }    }

When using:

    var c1 = create_counter();    c1.inc();   //1    c1.inc();   //2    c1.inc();   //3    var c2 = create_counter(10);    c2.inc();   //11    c2.inc();   //12    c2.inc();   //13

In the returned object, a closure is implemented, which carries the local variable x and cannot be accessed from external code. In other words, a closure is a function that carries a state, and its state can be completely hidden.

Closures can also program multi-parameter functions, but function parameters.

For examplex^yAvailableMath.pow(x,y)Function.x^2Orx^3We can use closures to create new functions.pow2Andpow3:

Function make_pow (n) {return function (x) {return Math. pow (x, n) ;}// create two new functions var pow2 = make_pow (2); var pow3 = make_pow (3); pow2 (5 ); // 25 pow3 (7); // 343
8. Match Function

We have noticed that we have used a new function,Match.pow(x,y)This function is used to return the specified power (y) of the base number (x). Match itself is a huge mathematical function library. Next we will learn a new function: random number.Math.random();The result is a random number between 0 and 1 (including 0, excluding 1)

For example, we are now producing a random number between 1 and 10:

<code class=" hljs xml">       </code>
<Script type = "text/javascript"> for (var I = 0; I <10; I ++) {alert (parseInt (Math. random () * 10);} </script> 9. eval function

eval();It is a function in JS that can convert characters into executable JS Code. Here are several examples:

Var a = "5 + 10"; alert (eval (a); // 15 var str = "function () {alert ('A ')}"; // directly change function equivalent var str = function () {alert ('A')}; str = eval ("+ str +") "); str ();

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.