Summary of JavaScript knowledge points - built-in objects

Posted by websteve on Tue, 15 Feb 2022 01:07:25 +0100

catalogue

1, What are built-in objects

2, Query document

2.1 MDN

2.2 how to learn methods in objects

3, Math object

3.1 Math overview

3.1.1 case exercise - encapsulating your own Math object

3.1.2 absolute value of math and three rounding methods

3.2 random number method (random)

3.2.1 case exercise - get a random number between two numbers and include these two integers

3.2.2 case exercise - random roll call

3.2.3 case exercise - number guessing game

IV. Date object (date)

4.1 use of date() method

4.1.1 must instantiate - Case - get the current time

4.1.2 parameters of date() constructor

4.2 date formatting

4.3 get the total millisecond form of date object

4.4 case exercise - Countdown effect

V. array objects

5.1 creation method of array object

5.2 check whether it is an array

5.3 methods of adding and deleting array elements

5.3.1 case exercise - filter array

5.4 array sorting

5.5 array index method

5.5.1} case exercise - array de duplication

5.6 converting arrays to strings

5.7 other methods

6, String object

6.1 basic package type

6.2 immutability of strings

6.3 return position according to characters

6.3.1 case exercises

6.4 return characters according to position (key)

6.4.1 case exercises

6.5 string operation methods (key points)

6.6 replacing strings and converting to arrays

There are three kinds of objects in JavaScript: custom object, built-in object and browser object

1, What are built-in objects

Built in objects: refer to some objects of JS language, which are used by developers and provide some commonly used or most basic and necessary functions (properties and methods)

  • The biggest advantage of built-in objects is to help us develop quickly
  • JavaScript provides several built-in objects: Math, Date, Array, String, etc

2, Query document

2.1 MDN

To learn how to use a built-in object, just learn how to use it commonly. You can learn by looking up the document, and you can query it through MDN / W3C

The Mozilla Developer Network (MDN) provides information about open web technologies, including HTML, CSS and the world wide web, as well as API s for HTML5 applications

MDN: MDN Web Docs (mozilla.org)

2.2 how to learn methods in objects

  1. Review the function of this method
  2. Check the meaning and type of parameters inside
  3. View the meaning and type of the return value
  4. Test through demo

3, Math object

3.1 Math overview

Math object is not a constructor, so it does not need new to call. It has numeric constants and function properties and methods. Math related operations (absolute value, rounding, maximum value, minimum value, etc.) can use members in math

Math - JavaScript | MDN (mozilla.org)

3.1.1 case exercise - encapsulating your own Math object

Use the object to encapsulate your own Math object, which has the maximum and minimum PI values

        var myMath = {
            PI: 3.1415926,
            max:function(){
                var max = arguments[0];
                for (var i = 1; i < arguments.length; i++){
                    if (arguments[0] > max){
                        max = arguments[i];
                    }
                }
                return max;
            },
            min:function(){
                var min = arguments[0];
                for (var i = 1; i < arguments.length; i++){
                    if (arguments[0] < min){
                        min = arguments[i];
                    }
                }
                return min;
            }
        }
        console.log(myMath.PI);
        console.log(myMath.max(1,5,9));
        console.log(myMath.min(1,5,9));

3.1.2 absolute value of math and three rounding methods

(1) Absolute value

        // 1. Absolute value method
        console.log(Math.abs(1)); // 1
        console.log(Math.abs(-1)); // 1
        console.log(Math.abs('-1')); //Implicit conversion converts string - 1 to numeric
        console.log(Math.abs('abc')); // NaN

(2) Rounding

        // 2. Three rounding methods
        // (1) Math.floor() round down to the smallest
        console.log(Math.floor(1.1)); // 1
        console.log(Math.floor(1.9)); // 1
        // (2) Math.ceil() round up to the maximum
        console.log(Math.ceil(1.1)); // 2
        console.log(Math.ceil(1.9)); // 2
        // (3) Math.round() is rounded. Other numbers are rounded, but *. 5 is special. It is rounded to the greater
        console.log(Math.round(1.1)); // 1
        console.log(Math.round(1.5)); // 2
        console.log(Math.round(1.9)); // 1
        console.log(Math.round(-1.1)); // -1
        console.log(Math.round(-1.5)); // -1

3.2 random number method (random)

The Math object random method, random(), returns a random decimal in the interval [0,1), that is, 0 < = x < 1

  • There are no parameters in this method
        console.log(Math.random());

3.2.1 case exercise - get a random number between two numbers and include these two integers

Math.floor(Math.random() * (max - min + 1)) + min;

Math.random() - JavaScript | MDN (mozilla.org)

        function getRandom(min,max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(getRandom(1,5));

3.2.2 case exercise - random roll call

        var arr = ['millet','Zhang San','Xiao Wang','leon','Li Lei']
        function getRandom(min,max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(arr[getRandom(0,arr.length-1)]);

3.2.3 case exercise - number guessing game

The program randomly generates a number between 1 and 10, and allows the user to enter a number

  1. If the number is greater than the number, you will be prompted: the number is large, continue to guess
  2. If the number is less than the number, you will be prompted: the number is small, continue to guess
  3. If it is equal to this number, the prompt is correct and the program ends
        function getRandom(min,max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        var random = getRandom(1,10);
        while(true) { 
            var num = prompt('Guess the number, please enter 1~10 A number between');
            if (num > random){
                alert('The number is big');
            } else if (num < random) {
                alert('The number is small');
            } else {
                alert('You guessed right')
                break;
            }
        }

IV. Date object (date)

Date object is a constructor, which can only be used after instantiation

The Date instance is used to process Date and time

Date - JavaScript | MDN (mozilla.org)

4.1 use of date() method

4.1.1 must instantiate - Case - get the current time

        var now = new Date();
        console.log(now)

4.1.2 parameters of date() constructor

If there is time in parentheses, the time in the parameter is returned.

  • For example, the date format character is' 2022-2-14 '
  • It can be written as new Date('2022-2-14 ') or new Date('2022/2/14')
        //For example, the date format string is' 2022-2-14 '
        var date1 = new Date('2022-2-14');
        console.log(date1);

4.2 date formatting

How to obtain the format of year month day hour: minute: second (0000-00-00 00:00:00)

You need to get the specified part of the date, and you need to get this format manually

Method nameexplaincode
getFullYear()Get current yeardateObj.getFullYear()
getMonth()Get current month (0-11)dateObj.getMonth()
getDate()Get the date of the daydateObj.getDate()
getDay()Get the day of the week (Sunday 0 to Saturday 6)dateObj.getDay()
getHours()Get current hourdateObj.getHours()
getMinutes()Get current minutesdateObj.getMinutes()
getSeconds()Get current secondsdateObj.getSeconds()
        // Format date
        var date = new Date();
        console.log(date.getFullYear());
        console.log(date.getMonth() + 1);
        console.log(date.getDate());
        console.log(date.getDay());
        // Case writing: Sunday, February 13, 2022 (actual date)
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dates = date.getDate();
        var arr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
        var day = date.getDay();
        console.log('Today is:' + year + 'year' + month + 'month' + dates + 'day' + arr[day]);

        //Format date hour minute second
        var date = new Date();
        console.log(date.getHours());
        console.log(date.getMinutes());
        console.log(date.getSeconds());
        //It is required to encapsulate a function to return the current time, minute and second format 00:00:00
        function getTime(){
        var time = new Date();
        var h = time.getHours();
        h = h < 10 ? '0' + h : h;
        var m = time.getMinutes();
        m = m < 10 ? '0' + m : m;
        var s = time.getSeconds();
        s = s < 10 ? '0' + s : s;
        return h + ':' + m + ':' + s;
        }
        console.log(getTime());

4.3 get the total millisecond form of date object

The Date object is based on the number of milliseconds from January 1, 1970 (world standard time)

Get the total number of milliseconds of Date through valueOf(), getTime()

        var date = new Date();
        console.log(date.valueOf()); //Total milliseconds from 1970.1.1
        console.log(date.getTime());
        // Simple writing
        var date1 = +new Date();
        console.log(date1);
        // H5 total milliseconds of newly added acquisition
        console.log(Date.now());

4.4 case exercise - Countdown effect

  1. Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't subtract hours, minutes and seconds
  2. Do it with a timestamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time
  3. Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to minutes and seconds)

Conversion formula

formulaexplain
D = parseInt (total seconds / 60 / 60 / 24);Calculation days
H = parseInt (total seconds / 60 / 60% 24);Calculate hours
M = parseInt (total seconds / 60% 60);Calculate score
S = parseInt (total seconds% 60);Calculate the current number of seconds
        function countDown(time){
            var nowTime = +new Date(); // Returns the total number of milliseconds of the current time
            var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time
            var times = (inputTime - nowTime) / 1000; //times is the total number of seconds remaining
            var d = parseInt(times / 60 / 60 / 24);
            d = d < 10 ? '0' + d : d;
            var h = parseInt(times / 60 / 60 % 24);
            h = h < 10 ? '0' + h : h;
            var m = parseInt(times / 60 % 60);
            m = m < 10 ? '0' + m : m;
            var s = parseInt(times % 60);
            s = s < 10 ? '0' + s : s;
            return d + 'day' + h + 'Time' + m + 'branch' + s + 'second';
        }
        console.log(countDown('2022-2-14 23:59:59'));
        var date = new Date();
        console.log(date);

V. array objects

5.1 creation method of array object

There are two ways to create array objects

  • Literal mode
  • new Array()
        // 1. Use array literal
        var arr = [1,2,3];
        console.log(arr[0]);;
        
        // 2. Use new Array()
        // var arr1 = new Array(); // Create an empty array
        // var arr1 = new Array(3); //  This 3 indicates that the length of the array is 3 and there are 3 empty array elements in it
        var arr1 = new Arry(1,2,3); //Equivalent to [1,2,3]

5.2 check whether it is an array

  • instanceof operator
  • Array. Isarray (parameter)
        // Detect whether it is an array
        // 1. instanceof operator
        var arr = [];
        var obj = {};
        console.log(arr instanceof Array);
        console.log(obj instanceof Array);

        // 2. Array. Isarray (parameter); The newly added method in H5 is supported by versions above ie9
        console.log(Array.isArray(arr));
        console.log(Array.isArray(obj));

5.3 methods of adding and deleting array elements

Method nameexplainReturn value
Push (parameter 1...)Add one or more elements at the end and pay attention to modifying the original arrayAnd returns the new length
pop()Delete the last element of the array, reduce the length of the array by 1, no parameters, and modify the original arrayReturns the value of the element it deleted
Unshift (parameter 1...)Add one or more elements to the beginning of the array. Pay attention to modifying the original arrayAnd returns the new length
shift()Delete the first element of the array, reduce the length of the array by 1, no parameters, and modify the original arrayAnd returns the value of the first element
        // 1.push()
        var arr1 = [1,2,3];
        // arr1.push(4,5,'red');
        console.log(arr1.push(4,5,'red')); // After the push, the returned result is the length of the new array
        console.log(arr1);

        // 2.unshift
        var arr2 = [1,2,3];
        // arr2.unshift('red','blue');
        console.log(arr2.unshift('red','blue'));
        console.log(arr2);

        // 3.pop()
        var arr3 = [1,2,3];
        console.log(arr3.pop()); // After pop, the returned result is the deleted element
        console.log(arr3);

        // 4.shift()
        var arr4 = [1,2,3];
        console.log(arr4.shift()); // After the shift, the returned result is the deleted element
        console.log(arr4);

5.3.1 case exercise - filter array

There is an array [2005004007009001100600]. It is required to delete more than 700 in the array and put the rest into the new array

        var arr = [200, 500, 400, 700, 900, 1100, 600];
        var newArr = [];
        for (var i = 0; i < arr.length; i++){
            if (arr[i] < 700) {
                newArr.push(arr[i]);
            }
        }
        console.log(newArr);

5.4 array sorting

Method nameexplainModify original array
reverse()To the order of elements in the array, no parametersThis method will change the original array and return a new array
sort()Sort array elementsThis method will change the original array and return a new array
        // Array sorting
        // 1. Flip array
        var arr1 = ['red', 'black', 'blue'];
        arr1.reverse();
        console.log(arr1);

        // 2. Array sorting (bubble sorting)
        var arr2 = [4,7,1,6,15,5,3,13,74];
        arr2.sort(function(a, b){
            // return a - b; // In ascending order
            return b - a; //In descending order
        });
        console.log(arr2);

5.5 array index method

Method nameexplainReturn value
indexOf()Finds the first index of a given element in an arrayReturns the index number, if any; If it does not exist, - 1 is returned
lastIndexOf()The last index in the arrayReturns the index number, if any; If it does not exist, - 1 is returned
        // Returns the index number method indexof (array element) of an array element
        var arr1 = ['red', 'black', 'blue', 'orage'];
        console.log(arr1.indexOf('blue'));
        console.log(arr1.indexOf('green')); //-1

        // Returns the array element index number method lastIndexOf (array element)
        var arr2 = ['red', 'black', 'blue', 'orage', 'green'];
        console.log(arr2.lastIndexOf('green'));

5.5.1} case exercise - array de duplication

Array ['a ',' B ',' Z ','d', 'x', 'a', 'Z', 'x', 'C'], ZIO finds the duplicate elements in the duplicate array

  • Core algorithm: traverse the old array, and then take the old array element to query the new array. If the element has not appeared in the new array, we will add it, otherwise we will not add it
  • How do I know if this element exists? Take advantage of the new array Indexof (array element). If - 1 is returned, it means that there is no such element in the new array
        // Encapsulating the de duplication function unique
        function unique(arr) {
            var newArr = [];
            for (var i = 0; i < arr.length; i++){
                if(newArr.indexOf(arr[i]) === -1){
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        }
        var demo = unique(['a', 'b', 'z', 'd', 'x', 'a', 'z', 'x', 'c']);
        console.log(demo);

5.6 converting arrays to strings

Method nameexplainReturn value
toString()Convert the array into a string to separate each itemReturns a string
join('separator ')Method is used to convert all elements in the array into a stringReturns a string
        // Convert array to string
        // 1. toString()
        var arr1 = [1,2,3];
        console.log(arr1.toString());

        // 2. join('separator ')
        var arr2 = ['red', 'blue', 'black'];
        console.log(arr2.join()); // red,blue,black
        console.log(arr2.join('-')); // red-blue-black
        console.log(arr2.join('&')); // red&blue&black

5.7 other methods

Method nameexplainReturn value
concat()Connect two or more arrays without affecting the original arrayReturns a new array
slice()Array interception slice(begin,end)Returns a new array of intercepted items
splice()Delete splice from array (the number to be deleted starts from the first few)Returns a new array of deleted items. Note that this will affect the original array

6, String object

6.1 basic package type

To facilitate the manipulation of basic wrapper data types, JavaScript also provides three special reference types: String, Number, and Boolean

Basic packing type is to wrap simple data types into complex data types, so that basic data types have properties and methods

        //What's wrong with the following code?
        var str = 'tom';
        console.log(str.length);
  • In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:
        // 1. Generate temporary variables and package simple data types into complex data types
        var temp = new String('tom');
        // 2. Assign a value to the character variable we declare
        str = temp;
        // 3. Destroy temporary variables
        temp = null;

6.2 immutability of strings

It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory

6.3 return position according to characters

All methods of string will not modify the string itself (the string is immutable), and the operation will completely return a new string

Method nameexplain
indexOf('character to find ', starting position)Returns the position of the specified content in the original string. If it is not found, it returns - 1. The starting position is the index index number
lastIndexOf()Look back and forward, only the first one that matches
        // A string object returns a position based on a string
        var str = 'Eat grapes without spitting grape skin, and spit grape skin instead of eating grapes';
        console.log(str.indexOf('eat'));
        console.log(str.indexOf('eat',1)); //Look back from where the index number is 1

6.3.1 case exercises

Find the location and number of occurrences of all o in the string "abcoasdowoejopp"

  • Core algorithm: first find the location where the first o appears. As long as the result returned by indexOf is not - 1, continue to find it later. Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search
        var str = 'abcoasdowoejopp';
        var index = str.indexOf('o');
        var num = 0;
        while(index !== -1){
            console.log(index);
            num++;
            index = str.indexOf('o',index + 1);
        }
        console.log('o The number of occurrences is:' + num);

 

6.4 return characters according to position (key)

methodexplainuse
charAt(index)Returns the character at the specified position (the index number of the index string)str.charAt(0)
charCodeAt(index)Gets the ASCII code (index index number) of the character at the specified position

str.charCodeAt(0)

str[index]Gets the character at the specified position

HTML5 and IE8 + support are equivalent to charAt()

        // 1. charAt(index) returns characters according to position
        var str = 'tom';
        console.log(str.charAt(2));
        // Traverse all characters
        for (var i = 0; i < str.length; i++){
            console.log(str.charAt(i));
        }

        // 2. charCodeAt(index) returns the character ASCII value of the corresponding index number. Purpose: to judge which key the user pressed
        console.log(str.charCodeAt(0));

        // 3. str[index] H5 added
        console.log(str[0]);

6.4.1 case exercises

Judge the character that appears the most times in a string 'abcbacbcabaccbacaaa', and count its times

  • Core algorithm: use charAt() to traverse this string
        var str = 'abcbacbcabacccbacaaa';
        var count = {};
        for(var i = 0; i < str.length; i++){
            var chars = str.charAt(i); //chars here refers to each character of the string
            if(count[chars]){
                count[chars]++;
            } else{
                count[chars] = 1;
            }
        }
        console.log(count);
        // Traversal object
        var max = 0;
        var ch = '';
        for(var key in count){
            if(count[key] > max){
                max = count[key];
                ch = key;
            }
        }
        console.log(max);
        console.log('The maximum number of characters is:' + ch);

6.5 string operation methods (key points)

Fang famingexplain
concat(str1,str2,str3...)The concat() method is used to connect two or more strings. Splice string, equivalent to +, + is more commonly used
substr(start,length)Starting from the start position (index number), the number taken by length (remember)
slice(start,end)Start from the start position and intercept to the end position, but end cannot (both of them are index numbers)
substring(start,end)Start from the start position and intercept to the end position. End cannot get it. It is basically the same as slice, but it does not accept negative values
        // 1. concat('string 1 ',' string 2 '...)
        var str1 = 'tom';
        console.log(str1.concat('jerry'));

        // 2. substr('intercept start position ',' intercept several characters')
        var str2 = 'When is the moon';
        console.log(str2.substr(2,2));

6.6 replacing strings and converting to arrays

methodexplain
replace('replaced character ',' replaced character ')Replace character, it will only replace the first character
split('separator ')Convert string to array
        // 1. Replace character ()
        var str1 = 'aabaabaac';
        console.log(str1.replace('a','b'));
        // There is a string 'aaacbcbcbaaa' that requires replacing all a's on both sides with*
        var str2 = 'aaacbcbcbaaa';
        while(str2.indexOf('a') !== -1) {
            str2 = str2.replace('a', '*');
        }
        console.log(str2);

        // Convert to character array 2 (split)
        var str3 = 'red,green,blue';
        console.log(str3.split(','));
        var str4 = 'red&green&blue';
        console.log(str4.split('&'));

 

Topics: Javascript Front-end