JavaScript summary 1.0— Basic syntax you need to know

    JS review 1.0 is mainly for the more important knowledge in js basic grammar, such as array, date, object, etc.

    1. Numeric correlation

    1. Add 0 in front of octal and 0x in front of hexadecimal in JS
    2. Maximum value: Number.MAXVALUE, this value is: 1.7976931348623157e+308 Minimum value: Number.MINVALUE, this value is: 5e-324
    3. console. log(Boolean(NaN)); // false
    4. Math.random() returns a random decimal: 0 =< x < 1 If you want to get a random integer between two numbers(including these 2 integers)
      Math.floor(Math.random() * (max - min + 1)) + min;
    5. The difference between null and undefined: null is an object (empty object pointer) representing "nothing", which is 0 when converted to a value; undefined is a primitive value representing "nothing", which is NaN when converted to a value
    6. Determine if a number is NaN: n!==n
    7. NAN is the numeric type Number type belonging to JavaScript


    2. Date related

    new Date()

    Date() date object is a constructor, so we need to use new to create our date object new Date() can pass in parameters:

    new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
    

    where year and month are mandatory parameters, others It is optional; if no parameter is passed, the current time is returned

    The parameter monthIndex is calculated from "0", which means that January is "0" and December is "11" When Date is called as a constructor and multiple parameters are passed in, if the value is greater than a reasonable range (such as 13 for the month or 70 for the minute), adjacent values will be adjusted. For example, new Date(2013, 13, 1) is equal to new Date(2014, 1, 1), which both represent the date 2014-02-01 (note that the month starts from 0). Other values are similar, new Date(2013, 2, 1, 0, 70) is equal to new Date(2013, 2, 1, 1, 10), both represent the same time: 2013-03-01T01:10:00

    var date = new Date();
      console.log(date.getMonth() + 1); // Month The returned month is 1 month smaller than the actual one, so remember +1 for the month
      console.log(new Date().getDay()); // Monday returns 1, Saturday returns 6 but Sunday returns 0
    


    Encapsulate and format the current time

    Encapsulate a function to return the current time format: x year x month x day x 08:08:08

    function getTimer() {
             let time = new Date()
             let year = time. getFullYear()
             let month = time. getMonth()+1
    
             let day = time. getDate()
             let arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
             let week = arr[time. getDay()]
             let h = time. getHours()
             h = h < 10 ? '0' + h : h
             let m = time. getMinutes()
             m = m < 10 ? '0' + m : m
             let s = time. getSeconds()
             s = s < 10 ? '0' + s : s
             return year+'year'+ month+'month'+day+'day'+week+h + ':' + m + ':' + s
         }
         console.log(getTimer());
    


    Get timestamp

    Indicates the number of milliseconds elapsed since January 1, 1970 at 0:00:00 (UTC, ie Universal Standard Time) Three methods can get the current timestamp

    console.log(new Date().getTime());
    console.log(Date.now());
    console.log(+new Date());
    

    Calculate the time consumed by a method

    // Method 1: Date.now()
    var start = Date. now();
    // Call a method that takes a certain amount of time:
    foo()
    var end = Date. now();
    var elapsed = end - start; // elapsed time in milliseconds
    //Replace Date.now() with +new Date()) is the third method
    
    //method two
    var start = new Date();
    foo()
    var end = new Date();
    var elapsed = end.getTime() - start.getTime();
    


    Copy date object

    Use the setTime method to assign a datetime to another Date object: dateObj.setTime(timeValue) timeValue is timestamp

    // Create a date object with the same time value
    let days = new Date(2020,10,3)
    let copy = new Date()
    copy.setTime(days.getTime());
    console.log(copy);
    

    Realize the countdown function

    It is implemented by subtracting the timestamp of the current time from the input time

    <body>
    <div>
        <span class="day"></span>
        <span class="hour"></span>
        <span class="minute"></span>
        <span class="second"></span>
    </div>
    
    <script>
        // 1. Get the element
        var day = document. querySelector('.day')
        var hour = document. querySelector('. hour')
        var minute = document. querySelector('. minute')
        var second = document. querySelector('. second')
        var inputTime = new Date(2022,10,1,20,45,12).getTime()
        countDown(); // Call the countDow function once to prevent the value from being blank when refreshing or entering the page for the first time
        // 2. Start the timer and execute it every second
        setInterval(countDown, 1000);
    
        //Every time the countDown function is called, the time difference between this time and the input date will be returned
        function countDown() {
            var nowTime = +new Date(); // returns the total milliseconds of the current time
            var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining
            var d = parseInt(times / 60 / 60 / 24) // days
            d = d < 10 ? '0' + d : d;
            day.innerHTML = d + 'day'
            var h = parseInt(times / 60 / 60 % 24); //times
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h + 'hour'
            var m = parseInt(times / 60 % 60); // minutes
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m + 'minute'
            var s = parseInt(times % 60); // current second
            s = s < 10 ? '0' + s : s
            second.innerHTML = s + 'seconds'
        }
    </script>
    </body>
    


    3. Array related

    Array method inventory

    will change the method of the original array The return value is a new array
    push、 unshift、pop、shift、reverse、sort、splice concat、filter、map、slice、sort、splice

    concat(): used to combine two or more arrays and return a new array
    every() : Tests whether all elements in an array can pass the test of a specified function. it returns a boolean
    some(): Test whether at least one element in the array passes the test implemented by the provided function, returning a boolean value
    fill() : Fills all elements in an array from the start index to the end index with a fixed value. Does not include termination index
    filter() : Creates a new array containing all elements that pass the test fulfilled by the provided function
    find() : Returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined
    forEach(): Executes the provided function once for each array element
    includes(): Determines whether the array contains a value in its entry, returning true or false
    Array.isArray(): Determines whether the passed value is an Array
    map(): Create a new array whose value is the result of calling the function in map for each element of the original array
    slice(): Return part of the array into a new array object selected from start to end (index value) end is not included, the return value is a new array containing the extracted elements
    splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place splice() returns an array containing the removed elements, or returns an empty array if no deletions are made. To access part of an array without modifying it use slice


    Convert array to string

    PS: Pay attention to the difference between join() and join('')

    // 1. toString() method
     var arr = [1, 2, 3, 4];
     console.log(arr.toString()); // 1,2,3
     // 2. join (separator) is commonly used
     var arr1 = [1,2,3,4];
     console.log(arr1.join()); // 1,2,3,4
     console.log(arr1.join(""));//1234
    


    4. String methods

    substr('The starting position of the interception (including this character)', 'A few characters are intercepted') not recommended

    substr() is not part of the main ECMAScript specification. Therefore, people are advised to use the standard String.prototype.substring() and String.prototype.slice() methods instead,

    substring: Returns the part between the start and end index of the string (excluding the end index value), or returns to the end of the string (when there is no second parameter)

    replace('replaced character', 'replaced character') : If there are multiple characters to be replaced, only the first character will be replaced
    split('separator') : convert character to array
    trim(): removes spaces from both ends of a string and returns a new string
    toUpperCase(): Returns the calling string value converted to uppercase
    toLowerCase(): Returns the calling string value converted to lowercase
    charCodeAt(index): Returns the ASCII code value of the character at the index number, if index is not a number, it defaults to 0


    5. Data Types

    Simple data type:

    • Simple data types are stored in the stack, and are automatically allocated and released by the operating system to store function parameter values, local variable values, etc.
    • When storing, the variable stores the value itself, including string, number, boolean, undefined, null and other basic data types and value types

    Complex data type:

    • The hexadecimal address is stored in the complex data type stack, and this address points to the real data in the heap. The heap is generally allocated and released by the programmer. If the programmer does not release it, it will be recycled by the garbage collection mechanism.
    • When storing, the address (reference) is stored in the variable, such as Object, Array, Date, Function, etc.


    6. Three ways to create objects

    Using literals to create objects:

    // var obj = {}; // creates an empty object
     var obj = {
             name: 'A',
             sayHi: function() {
                 console.log('hi');
    
             }
         }
         //The method of using object properties: object name. property name or object name ['property name']
          console.log(obj.name);
         console.log(obj['name']);
         obj. sayHi();
    

    Use new Object to create an object

    var obj = new Object(); // creates an empty object
         obj.name = 'A;
         obj. sayHi = function() {
                 console.log('hi');
    
             }
    

    Using the constructor to create an object

    The constructor is to encapsulate some of the same properties and methods in the object into a function Note:
    - The first letter of the constructor name should be capitalized
    - Calling the constructor must use new
    - properties and methods must be preceded by this

    function Person(name) {
     this.name = name;
     this. sayHi = function(sayHi ) {
    console.log(this.name+'hi');
        }
     }
    var stu = new Person('A'); // The calling function returns an object
    console.log(stu.name);
    stu.sayHi('Hello')
    


    7. Program debugging

    The process of breakpoint debugging:
    1. Press F12 in the browser --> sources --> find the file to be debugged --> set a breakpoint in a certain line of the program
    2. Watch: Monitoring, through watch, you can monitor the change of the value of the variable, which is very commonly used.
    3. Press F11 to execute the program step by step, and let the program execute line by line. At this time, observe the change of the value of the variable in the watch.


    8. Pre-parsing

    Pre-parsing is divided into variable pre-parsing and function pre-parsing
    Variable promotion: Promote all variable declarations to the front of the current scope and do not promote assignment operations (that is, they are currently undefined)
    Function promotion: hoist all function declarations to the front of the current scope without calling the function variables declared by var are hoisted, let and const are not hoisted

    example 1

    var num = 1
         foo();
         function foo() {
             console. log(num);
             var num = 20;
         }
     //value is undefined
         // Equivalent to performing the following operations
         // var num;
         // function foo() {
         // var num;
         // console. log(num);
         // num = 20;
         // }
         // num = 1;
         // foo();
    


    example 2

    var num = 1
     foo();
     var foo = function () {
         console. log(num);
       var num = 20;
     }
    //report an error, foo is not a function, pay attention to compare and distinguish it from the previous question, because the value of foo promoted at this time is undefined, not a function
    


    example 3

    foo();
         console.log(b);//1
         console.log(a);//Error, a is not defined, because a is defined as a local variable inside the function
    
         function foo() {
             var a = b = 1;
             console.log(a); //1
             console.log(b);//1
         }
    // var a = b = 1 is equivalent to
         // var a; a is a local variable that can only be used inside the function
         // a = b = 1; b is assigned directly, without var declaration, when global variable
    


    9. Details

    • The output of prompt and alert is string type
    • Only - * / adding numbers can realize the implicit conversion of numbers, and + cannot
    • return can only return one value, and the returned result is the last value eg: return a,b,c actually returns c
    • When you are not sure how many parameters the function has to pass, you can use arguments to get it. The arguments object stores all the actual parameters passed. It is a pseudo-array with a length attribute and index, but there is no method such as pop() of the array
    • Strings are immutable: let str = 'a' ; str = 'b', reassignment to str will re-open up space in memory, so a large number of concatenated strings will affect efficiency

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)

    Win10 远程计算机或设备将不接受连接