[JavaScript learning notes] things about built-in objects (all details, I've collected them!)

Built in object

There are three types of objects in JavaScript:

  • custom object
  • Built in object
  • Browser object

The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS

  • Built in objects refer to the built-in 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, Data, Array, String

Check documents

MDN

To learn how to use a built-in object, just learn how to use its common members. We can query it through MDN/W3C.
Mozilla Developer Network (MDN) provides information about open web technology (Open Web), including HTML,CSS and API s for World Wide Web and HTML5 applications.

Website address

How to learn objects

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

Math object

max method

        console.log(Math.PI);
        console.log(Math.max(1,99,3));
        console.log(Math.max(1,99,'41 teacher'));//NaN
        console.log(Math.max());//-Infinity

Encapsulate your own mathematical objects

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

Random number method (random)

  • random() returns a random effective number [0,1]
  • This method is different from the parameter
  • Code verification
        console.log(Math.random());

Get the random integer between two numbers and include these two integers

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

Enumeration of other math methods

methodeffect
Math.PIPI
Math.floor()Round down
Math.ceil()Round up
Math.round()Round to the nearest - 3.5 - > - 3
Math.abs()absolute value
Math.max()Maximum
Math.min()minimum value

Case: number guessing game

  • 1. Randomly generate an integer of 1-10. We need to use math Random() method
  • 2. The kitchen knife needs to be in the correct position all the time, so it needs to be circulated all the time
  • 3. The while loop is simpler
  • 4. Core algorithm: use if else if multi branch statement to judge greater than, less than and equal to.
        function getRandom(min,max){
            return Math.floor(Math.random()*(max-min+1))+min;
        }
        var random=getRandom(1,10);
        while(true){
            var num=prompt('Guess what? Input 1-10 A number between');2
            if(num>random) alert('Guess big!');
            else if(num<random) alert('Guess it's small!');
            else{
                alert('You guessed right!');
                break;
            }
        }

Date object

Date() Date object is a constructor. We must use new to call to create our date object.
Date object is different from Math object. It is a constructor, so we need to instantiate it before using it.

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

Date formatting

Method nameexplain
getFullYear()Get current year
getMonth()Get current month (0-11)
getDate()Get the date of the day
getDay()Get day of the week (0-6)
getHours()Get current hour
getMinutes()Get current minute
getSeconds()Get current seconds

Day of year

        var date = new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var days=date.getDate();
        var arr=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
        var weekday=date.getDay();
        console.log('Today is'+year+'year'+month+'month'+days+'day'+arr[weekday]);

Hour, minute and second

        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());

Date total milliseconds

How many milliseconds have passed since 1970.1.1.

  • 1. Use valueof() getTime()
  • 2.+new Date() returns the total number of milliseconds
  • 3.H5 add the current milliseconds (now)
        var date = new Date();
        console.log(date.valueOf());
        console.log(date.getTime());

        var date1 =+new Date();
        console.log(date1);

        console.log(Date.now());

Case: Countdown

  • Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't fry with hours, minutes and seconds. For example, if you subtract 25 points from 05 points, the result will be negative.
  • 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
  • Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to minutes and seconds)
        function countDown(time){
            var nowTime = +new Date();//Returns the total number of milliseconds of the current time
            var inputTime = +new Date(time);//The total number of milliseconds of user input time returned
            var times = (inputTime -nowTime)/1000;//time is the total number of seconds left
            var d=parseInt(times/60/60/24);//day
            d=d<10?'0'+d:d;
            var h=parseInt(times/60/60%24);//hour
            h=h<10?'0'+h:h;
            var m=parseInt(times/60%60);//minite
            m=m<10?'0'+m:m;
            var s=parseInt(times%60);//second
            s=s<10?'0'+s:s;
            return d+' day '+h+' hour '+m+' minute '+s+' second ';
        }
        console.log(countDown('2021-5-1 18:00:00'))

Array object

Two ways to create mathematical 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(2);//This 2 means that the length of the array is 2
        var arr2=new Array(2,3);//This 2 is the first element 2 in the array
        console.log(arr1);

Detect whether it is an array

  • instanceof operator, which can be used to detect whether it is an array
        var arr=[];
        console.log(arr instanceof Array);
  • Array. Isarray (parameter) a new method in H5, which is supported by ie9 and above
        var arr=[];
        console.log(Array.isArray(arr));

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, and 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

Array sorting

Method nameexplainReturn value
reverse()Dumping the order of elements in the array, no parametersThis method will change the original array and return a new array
sort()Sort the elements of the arrayThis method will change the original array and return a new array

Note that there will be some bug s when double digits appear in sort, such as

        var arr1=[13,4,77,1,7];
        arr1.sort();
        console.log(arr1);//1 13 4 7 77 will look at the first digit first

Array index method

Method nameexplainReturn value
indexOf()Finds the first index of a given element in an arrayReturns the index number if it exists or - 1 if it does not exist
lastIndexOf()The last index in the arrayReturns the index number if it exists or - 1 if it does not exist

Convert array to string

Method nameexplainReturn value
toString()Convert the array into a string, separating each item with a commaReturns a string
join('separator ')Method is used to convert all elements in the array into a stringReturns a string
        var arr=[1,2,3];
        console.log(arr.toString());
        var arr1=['green','blue','yellow'];
        console.log(arr1.join('-'));//Can be empty separator

Inquiry after class

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

slice() and slice() have basically the same purpose. I suggest you focus on slice()

case

1. Filter array

There is an array containing palace purple [1500120020021001800]. It is required to delete the palace purple in the array that exceeds 2000 and put the rest into the new array

        var arr=[1500,1200,2000,2100,1800];
        var newArr=[];
        for(var i=0;i<arr.length;i++){
            if(arr[i]<2000){
                // newArr[newArr.length]=arr[i];
                newArr.push(arr[i]);
            }
        }
        console.log(newArr);

2. Array de duplication

        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(['c','a','a','a','b','b']);
        console.log(demo);

String object

To facilitate the operation of basic 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.

Immutability of string

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

Because our strings are immutable, we should not splice a large number of strings

Return position according to character

All methods of string will not modify the string itself (the string is immutable), and a new string will be returned after the operation is completed.

Method nameexplain
indexOf('character to find ',' starting position ')Returns the position of the specified content in the original string. If it cannot be found, it returns - 1. The starting position is the index index number
lastIndexOf()Look back and forward, only the first one that matches

Return characters according to position (emphasis)

Method nameexplainReturn value
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 positionstr.charCodeAt(0)
str[index]Gets the character at the specified positionHTML5 and IE8 + support are equivalent to charAt()

String operation method (emphasis)

Method nameexplain
concat(str1,str2,str3...)concat() method is used to connect two or more strings and splice strings, which is equivalent to +, + is more commonly used
substr(start,length)Start at the start position (index number), and get the number by length. Keep this in mind
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. The end position cannot be found. It is basically the same as slice, but it does not accept negative values
replace('replaced character ',' replaced character ')It will only replace the first character
split('separator ')Turn array
        var str='red&green&yellow';
        console.log(str.split('&'));

Inquiry after class

  • toUpperCase() / / convert to uppercase
  • toLowerCase() / / convert to lowercase

case

1. Find the position and number of occurrences of a character

Find the location and number of occurrences of all o in the string 'abcoefoxyozzopp'

        var str='abcoefoxyozzopp';
        var index=str.indexOf('o');
        var num=0;
        while(index!== -1){
            num++;
            console.log(index);
            index=str.indexOf('o',index+1);
        }
        console.log('Number of occurrences:'+num);

2. Characters with the most occurrences

        var str='abcoefoxyozzopp';
        var o={};
        for(var i=0;i<str.length;i++){
            if(o[str[i]]){
                o[str[i]]++;
            }else{
                o[str[i]]=1;
            }
        }
        var max=0;
        var ch='';
        for(var k in o){
            if(o[k]>max){
                max=o[k];
                ch=k;
            }
                
        }
        console.log(max+',The maximum number of characters is:'+ch);

3. Replace all o with*

        var str='abcoefoxyozzopp';
        while(str.indexOf('o')!==-1){
            str=str.replace('o','*')
        }
        console.log(str);

Keywords: Javascript

Added by Waldir on Sat, 05 Mar 2022 03:01:49 +0200