Web front end lesson 28 – JS variable promotion, built-in objects (Math & date)

Time:2021-10-22

1. Variable lifting

The JavaScript engine works by parsing the code, obtaining all declared variables, and then running the code line by line from top to bottom

Therefore, all non function variable declaration statements will be promoted to the head of the code. JavaScript’s mechanism for reading variables is called variable promotion

Note that variable promotion is only for   The variable declared by the VaR command is valid if it is not used   The variable declared by VAR command will not be promoted

2. Variable scope

Variables declared by VaR are called local variables. Local variables only take effect within the scope of their function. The scope of variable effectiveness is called variable scope

If not applicable   Var declaration means that the variable takes effect in the whole file, that is, the global variable

3. First class citizens

In many traditional languages (C / C + + / Java / C #), functions exist as second-class citizens,

Because, in addition to calling the function, if you want to pass the function as a parameter to another function, or assign it to a local variable, or as a return value, you need to pass the function pointer   Make some twists and turns in special ways such as pointer and delegate;

However, functions in JavaScript are first-class citizens. They not only have the use characteristics (declaration and call) of all traditional functions, but also can assign values, pass parameters and return like simple values. Such functions are also called first-class functions   Function) or first-class citizen.

Functions in JavaScript are in the same position as other data types (numeric value, string, Boolean value, etc.), and functions can be used where other data types can be used

4. Function promotion

The function processing mechanism of JavaScript engine is the same as that of variables   For the function declared by the function command, the whole function will be promoted to the code header like the variable declaration

Note that function promotion is only for   The function declared by the function command is valid

5. Variable promotion in function

Like the global scope, variable promotion will also occur inside the function, that is, using   No matter where the variable declared by VAR command is, the variable declaration will be promoted to the head of the function body.

6. Default values of function parameters

Example: function   func(num){

num=num || 1;   //  It can be understood as a three item conditional expression: judgment condition? true:false;

      return num;

     }

func();   //  The return value is 1

The above method will affect the function parameters   Num performs a Boolean operation, and the judgment result is   When true, Num is returned and the result is   False returns 1, which avoids the failure of function call caused by forgetting to write parameters

However, in addition to undefined, the Boolean values of 0, empty character and null are also false, that is, in the above function, if the parameter is equal to 0 or empty string, the default value of 1 will also be returned if there are parameters

7. Value transfer and address transfer

The content transfer method of the basic data type (numeric value, string, Boolean value) is value transfer (pass)   by   value)

The content transfer method of composite data types (arrays, objects, other functions) is address pass   by   reference)

Function




    var num=20;
    function consulate(x) {
        x*=3;
        console.log(x);
        return x/2;
    }
    var res=consulate(num);
    console.log(res);
    console.log(num);

Web front end lesson 28 - JS variable promotion, built-in objects (Math & date)

8. Parameters with the same name of the function

If the function has a parameter with the same name, the last parameter value will be taken when calling. An example is as follows

var num1=20;
    var num2=30;
    function consulate(x,x) {
        x*=3;
        console.log(x);
        return x/2;
    }
    var res=consulate(num1, num2);
    console.log(res);

//The operation results are: 90 and 45

If the last parameter is not provided when calling the function, the value of the function will be displayed as   undefined

In principle, try not to write parameters with the same name, and several parameters are set when defining the function. Try to ensure that they are consistent with the definition when calling

9. Arguments object

JavaScript allows functions to have an indefinite number of parameters, and the arguments object can read all parameters inside the function body,

The arguments object contains functions   Runtime   All parameters

Arguments [0] represents the first parameter of the function, arguments [1] represents the second parameter, and so on

The arguments object can only be used inside a function. An example is as follows

function arg(x) {
        console.log(arguments[0]);  // 1
        console.log(arguments[1]);  // 2
        console.log(arguments[2]);  // 3
    }
    arg(1,2,3);

In addition, in addition to reading parameters, the arguments object can also assign values to parameters, which take precedence over the actual parameters of the calling function

Syntax: arguments [0] = 10;

In addition, you can judge how many parameters are taken during the function call through the length attribute of the arguments object

Syntax: arguments. Length;

The data type of arguments belongs to   Object, not array!

10. Eval function

The eval () function evaluates a string and executes the JavaScript code in it

Syntax: Eval (string);   (function: execute the string as a statement)

This method only accepts   Original string   As a parameter, if   If the string parameter is not the original string, the method will return without any change

So don’t worry about   Eval() function transfer   String object as a parameter

An exception will be thrown if the eval() function is illegally called or passed in parameter errors during use

var str='var eva="car"';
    eval(str);
    console.log(eva);  // When eval() function is not used, the error variable has no exception defined!

11. Instanceof type judgment

Typeof is used to detect and identify the original data type, while instanceof is used to determine whether a variable belongs to an instance of a type

Typeof syntax: typeof   Variable name, The return value is a data type

Instanceof syntax: variable name   instanceof   Data type, The return value is Boolean

12. Math object

Math object is a built-in object of JavaScript, which provides a series of mathematical constants and mathematical methods

The object has no constructor math (), so it cannot generate an instance. All properties and methods must be called on the Math object itself

Math object property that represents a read-only mathematical constant

Math.E   Constant e (2.718281828459045)

Math.LN2   Natural logarithm of 2 (0.6931471805599453)

Math.LN10   Natural logarithm of 10 (2.302585092994046)

Math.LOG2E   Logarithm of E based on 2 (1.4426950408889634)

Math.LOG10E    Logarithm of E based on 10 (0.4342944819032518)

Math.PI   Constant PI (3.141592653589793)

Math.SQRT1_ two     The reciprocal of the square root of 2, i.e. the square root of 1 / 2 (0.7071067811865476)

Math.SQRT2   Square root of 2 (1.4142135623730951)

13. Math object method

Math. Round (x), round

Math. Floor (x), rounded down (returns the largest integer less than the parameter value)

Math.ceil (x), rounded up (returns the smallest integer greater than the parameter value)

Math.abs (x), return the absolute value of the parameter

Math.max (x, y, Z,…, n), returns the largest value in the parameter

Math.min (x, y, Z,…, n), returns the smallest value in the parameter

Math.pow (x, y), return with X   Is the base and Y is the power of the exponent

Math.sqrt (x) returns the square root of the parameter value. If the parameter is negative, Nan is returned

Math.log (x), return with   E is the natural logarithm of the base

Math.exp (x), return constant   E   Exponential value of x power

Math.sin (x), return the sine value of the parameter. X is an angle expressed in radians, and the return value is between – 1 and 1. Multiply the angle by 0.017453293 (2pi / 360) to convert it into radians

Math. Cos (x), return the cosine value of the parameter, X is a numeric value, and the return value is between – 1 and 1

Math.asin (x), return the arcsine value of the parameter, X is a value between – 1.0 and 1.0, and return the radian value between – pi / 2 and PI / 2,   Nan is returned when x exceeds the range of – 1.0 ~ 1.0

Math.acos (x) returns the inverse cosine value of the parameter. X is a value between – 1.0 and 1.0, and returns the radian value between 0 and PI,   Nan is returned when x exceeds the range of – 1.0 ~ 1.0

Math.tan (x), returns the tangent value of the parameter, where x is an angle expressed in radians

Math.atan (x), return the arctangent value of the parameter, X is a numeric value, return  – PI/2   reach   Value between PI / 2 radians

Math. Random(), returns a pseudo-random number between 0 (inclusive) and 1 (exclusive)

14. Math. Random() method

Creates a random integer within a specified range

function getRandomNumber(min,max) {
        return Math.floor(Math.random()*(max-min)+min);
    }
    console.log(getRandomNumber(10,100));

Create a random verification code of a certain length

function getRandomNumber(min,max) {
        return Math.floor(Math.random()*(max-min)+min);
    }
    function getRandomVerify(len) {
        var verifyCode='';
        var verifyCharSet='AB[email protected]#$%^&*';
        var maxNum=verifyCharSet.length
        for (var i=0;i<len;i++){
            var index=getRandomNumber(0,maxNum);
            var verifyStr=verifyCharSet[index];
            verifyCode+=(verifyStr+' ');
        }
        return verifyCode
    }
    console.log(getRandomVerify(5));

15. Date object

The date object is an operation interface for JavaScript to provide date and time

Inside JavaScript, all dates and times are stored as an integer

This integer is the number of milliseconds from the current time to 00:00:00 on January 1, 1970. The positive and negative range is 100 million days before and after the base time

Like math objects, JavaScript is   The date object provides many built-in methods

16. Date() function

The date() function can be called directly by the date object to return a string of the current date and time

Syntax example: VAR   date=Date();

With or without parameters, a direct call to date always returns the current time

17. Date (date string)|   Date (parameter) constructor

The date object is a constructor. Using the new command on it will return an instance of the date object

Syntax example: VAR   date=new   Date(‘August 21,1999’);

If no parameter is added, it representsReturns the object at the current time, if you add aDate stringAs a parameter, the time corresponding to the string is returned

Add a date parameter and return the time corresponding to the parameter. Syntax example: VAR   date=new Date(year,month,day,hours,minutes,seconds,ms),

When using the date parameter, the year and month must be filled in, and other parameters can be omitted (0 by default),The month is from 0 to 11

18. Date calculation

When the date is stored in JavaScript, it is stored in milliseconds from zero on January 1, 1970.

Therefore, when subtracting two date objects, the return value is the number of milliseconds between them; When adding two date objects, the return value is the connected two strings.

19. Get series methods of date object

getTime(); Returns the number of milliseconds from the instance object to zero on January 1, 1970, which is equivalent to the valueof method

getDate(); Returns the day of each month (starting from 1) corresponding to the instance object

getDay(); Returns the day of the week, Sunday is 0, Monday is 1, and so on

getYear(); Returns the number of years from 1900

getFullYear(); Returns a four digit year

getMonth(); Return month (0 for January, 11 for December)

getHours(); Return hours (0 to 23)

getMinutes(); Return minutes (0 to 59)

getSeconds(); Return seconds (0 to 59)

getMilliSeconds(); Return milliseconds (0 to 999)

Example code:

var date=new Date();
    var tim1=date.getDate();
    var tim2=date.getDay();
    console.log(tim1);
    console.log(tim2);
var today=new Date();
    var lastDay=new Date(today.getFullYear(),11,31,23,59,59,999);
    var msDay=24*60*60*1000;
    var leftDays=Math.floor((lastDay-today)/msDay)
    console.log(leftDays);