JavaScript functions and built-in objects

Author : houxue   2023-04-11 09:45:04 Browse: 919
Category : JavaScript

Abstract: 1.Functions of js **Defining methods in Java Public return value type void/int method name (parameter list) { Method b...

1.Functions of js

**Defining methods in Java
    Public return value type void/int method name (parameter list) {
        Method body;        Return value;    }
    public int add(int a,int b){
        int sum=a+b;
        return sum;
    }

**There are three ways to define functions in js
    ***1)In the parameter list of the function, there is no need to write var, just write the parameter name directly
       2)Js functions can have return values, which can be directly returned using the return keyword without declaring the return value type
      3)Js does not have the concept of overloading methods, and the functions defined later will overwrite the functions written earlier
      4)The number of formal parameters and actual parameters in JavaScript can be inconsistent, but they can still be called.
      5)Each function hides an array called arguments, which is used to receive the actual parameter values passed during function calls
      6)After the arguments array accepts the actual parameters, it will assign values to the formal parameters one by one, from left to right
        If the number of actual parameters is greater than the formal parameters, the remaining actual parameters will be discarded
    Actual parameter<formal parameter: NaN
    Actual parameters>formal parameters: Discard the parameters after taking the previous actual parameters.

    Note: All data received by the form is of type string
    String comparison number String will automatically convert to number first and then compare;

    Define Objects
Method 1
    Constructor with parameters
    Function object name (formal parameter){
        Define attributes:
        Definition method:
    }
example:
function Person(name,age){  this represents the object currently called
    //Defining Attribute Assignments
    this.name=name;
    this.age=age;
    //Definition method
    this.say=function(){
        alert("This is a method for an object");
    }
}   
var     Variable name=new  Object Name
//Create an object
var  p=new Person("Gouwa",14);
//View attribute values
document.write(p.name);
document.write(p.age);
//Calling methods 
p.say();

//Using for in to traverse objects
for(var i in p){
document.write(p[i]+"<br/>");

Method 2
Parameterless posterior function
Define Objects
function Person(){

}
//create object
var p=new Person();
//append attribute
p.name="zjj";
p.age=14;
//additional methods
p.say=function(){
        alert("++");
}

The third way
Using built-in objects Object objects can serve as templates for any object

/*
create object
var p=new Object(); 
*/
//Append attribute
p.name="zjj";
p.age=14;
//Additional methods
p.say=function(){
        alert("++");
}

Method 4: Using literal constants to create objects in the JSON language
 var p={
    //Define attributes
    **Separate each attribute with a comma
      Attribute name enclosed in quotation marks
     Attribute names and values are used with:
    The last one should not be separated by commas
    Attribute Name Attribute Value
    “name”:“Tiedan",(comma)
    "age":20,
    "say":function(){
        alert("');
    }
}

Adding Methods to Array Objects Using Prototype Properties
What is a prototype
    1) Each object in JS contains prototype attributes
    2) If a method is added to the prototype of an object, the added method will automatically be added to the current Object.
    3) The role of prototypes: adding methods to built-in objects

    function Array(){
        //attribute
        this.prototype=new Prototype();//Prototype object pseudocode
        this.search=function(){
        }       
    }
    function Prototype(){
        this.search=function(){

        }
    }
    grammar:
    /*
    Add a search and max method to the Array
    */
    Array.prototype.search=function(traght){
        for(var i=0;i<this.length;i++){
        if(this[i]==traght){
        return 1;
        }
       }
        return -1;  
    }

    js function

    The first method:
        ****Using a keyword, function
        ***Function method name (formal parameter list){
            Method body;
            The return value can be optional (according to actual needs);
        }
        code
        Using the first method
        function test(){
            alert("sghjak");
        }
        //Call method
        Test (actual parameter list);
        //Define a method with parameters to add two numbers
        function add1(a,b){
            var sum=a+b;
            alert(sum);
        }
        //add(2,3);
        //There is a return worth the effect
        function add2(a,b){
            var sum=a+b;
            return sum;
        }
        alert(add2(3,4,5));
        The second method
            ****Anonymous function
                var add=function(parameter list){
                    Method body and return value;                    }
                ***code
                //Functions created in the second method
                var add3=function(m,n){
                    alert(m+n);
                    }
                //Calling methods
                add3(4,5);
            The third method; (Less used, understanding)
                ****Dynamic function
                ***Using a built-in object Function in js
                    var add=new Function("Parameter List","'Method body and return value");
                **code
                var canshu="x,y";
                var fahgfati="var sum; sum=x+y;return sum;";
                var add3=new Function(canshu,fangfati);
                alert(add3(4,5));

2.String object

***The length of the attribute length string
***method
    var str1=new String("hello");
    var str2=new String("hello");
    valueof();This method returns whether the contents of the object are equal
    str1.valueof()==str2.valueof();
    str1==str2  false
    var str="abc";
    var str2="abc";
    str1==str2  true;
    (1)HTML related methods
        -bold():Bold
        -fontcolor:Set the color of the string
        -fontsize():Set font size

        -link():Display strings as hyperlinks
            ***str4.link("hello.html");
        -sub()  sup() :Subscript and superscript
    (2)Similar methods to Java
        -fontcolor();Add color directly to the string
        document.write(str.fontcolor("#0000ff");(Red Green Blue)
        -concat():Connection String
            **//concat method
            var str1="abc";
            var str1="dfg";
            document.write(str1.concat(str2));
        -chadAt():Returns a string at the specified position
            **var str1="abcfegh";
            document.write(str1.charAt(20);//The string position does not exist, returning an empty string
        -indexOf(): Return string position
            **var str="abcfegh";
            document.write(str.indexof("w")); //Character does not exist, return -1
        -split:Cut a string into an array
            **var str="a-b-c-f-e-g-h";
            var ar1=str.split("-");
            document.write(arr1.length);
        -replace(); Replace String
            *Pass two parameters
                --Original character for the first parameter
                --The character to replace with
            ***var str="abcfegh";
            document.write(str.replace("a","Q");
        -substr(start,length)和 substring( start,end)
            **var str="abcfeghsdfs";
            //document.write(str.substr(5,5);  //Starting from the fifth digit, truncate five characters backwards
                    **Starting from the first digit, truncate backward by several digits
            document.write(str.substring(3,5);  //From which position to which position to end [3 ,5)
                **Starting from position and ending at position, but excluding the last digit

3.Number object

 Method 1: Define a number object
    var num1=new  Number(20);
    var num2=new  Number(20);
    num1==num2;   false;
    num1.valueof()==num2.valueof();  true;
Method 2
    var num1=20;
    var num2=20;
    num1==num2;  true

    var   b1=new Boolean(true);
    var   b2=new Boolean(true);
    b1==nb2;   false;
    b1.valueof()==b2.valueof();  true;

4.Array object

    **What is an array?
    **Using variable var m=10;
    **The definition of arrays in Java int [] arr={1,2,3};
**Definition methods (three types)
    The first type: var arr=[1,2,3];
    The second method is to use built-in objects Array objects
    var arr1=new Array(5);// Define an array with a length of five
        arr1[0]="1";
    Third method: Use built-in object Array
    var arr2=new Array(3,4,5);// Define an array with elements 3, 4, and 5
    *There is an attribute length in the array to obtain the length of the array
    alert(arr3.length);    *Arrays can store data of different data types.
    **Create arrays (three types)
    /*
    The length of the array will vary with the addition of elements, so there is no need to worry about index position out of bounds exceptions
    js can store any type of element
*/
- var arr=[10,“hello”,true ];
var arr=new Array();
        arr[1]="a";
        arr[2]="b";
        arr[3]="c";
-var arr=new Array(3);//An array with a length of 3
-var arr=new Array(3,4,5);//The elements in the array are 3, 4, 5
**Property: length View the length of the array
**method
    -concat() method:Connection of arrays
        var arr=[1,2,3];
        var arr1=[,5,6];
        document.write(arr.concat(arr1));
    -join();Using the specified string, concatenate all elements of the array together to form a new string.
        var arr=new Array();
            arr[1]="a";
            arr[2]="b";
            arr[3]="c";
            document.write(arr.join("-"));
            result a-b-c
    -push();Add elements to the end of the array and return the new length of the array
            **If you are adding an array. At this point, add the array as a whole string
            var arr=new Array();
            arr[1]="a";
            arr[2]="b";
            arr[3]="c";
            document。write(arr.push("gsdjkfsad");
    -pop():Represents deleting the last element and returning the deleted element
            var arr=["ff","fasdf","sdf","sdfaf"];
            document.write(arr.pop());
    -reverse():Reverse the order of elements in an array
            var arr=["ff","fasdf","sdf","sdfaf"];
            document。write(arr.reverse());

5.Date Object

Obtain the current time in Java
Date data=new Date();// Retrieve the current system date and time
Java: SimpleDateFormat object yyyy mm dd format
//Format: January 14, 2018 16:35:30

    //toLocaleString()
Obtain the current time in JS

var date=new Date()
//Get the current time
document.write(date)
//Convert to a custom format
data.toLocaleString();
**Method for Obtaining Years
getFullYear(); Obtain the current year
*Obtain the current month method
getMonth(); Get the current month
***If you want to obtain an accurate value from 0 to November, add 1;
**Get the current week
getDay(); Week. The returned values are (0-6);
Foreign friends, consider Sunday as the first day of the week, and the value returned on Sunday is 0
The values returned from Monday to Saturday are 1-6;
**Get the current day
getDate(); Get the current day
**Get the current hour
GetHours() Get hours
**Get the current minute
getMinutes(); minute
**Get the current second
getSeconds(); second
**Get milliseconds
getTime()
Returns the number of milliseconds since January 1970
**Application Scenario
***The effect of using milliseconds to process caching (without caching)
http://www.baidu.com? Msec

6.Math Object

*Mathematical operations
The methods inside are all static, and you can directly use the Math. method ();
1)ceil(x); Round up if there are decimals, add one directly
2)floor(x); Round down if there are decimal parts, discard the decimal parts directly and keep the integer digits
3)round(x); rounding
4) Random() obtains a random number (pseudo random number) 0-1 [0 1]
5) Max() returns the maximum value
6) Min() returns the minimum value
Obtain random numbers ranging from 0 to 9
Math.random()*10
Math.max(10,5,60);
Math.min(10,50,-2);

7. Global functions of JS

As it does not belong to any object, write the name directly and use it
**Eval() executes JS code (if the string is a JS code, use the method to execute it directly)
******var str="alert("1234");";
eval(str);
**encodeURI(); Encode characters
**DecodeURI () Decodes numbers
EncodeURIComponent() and decodeURIComponent();
**IsNaN determines whether the current string is a number
var str="asd";
alert(isNaN(str));
**If it is a number, return false
**Returns true if it is not a number
**ParseInt() type conversion
varstr="123";
document.write(parseInt(str));

8.js functions are similar to overloading

**What is overload? Same method name, different parameters
Does the overload of JS exist? non-existent
**Call one method after another
**Save the existing parameters in an array called arguments
**Is there an overload in JS? (Interview topic)
(1) There is no overload in JS
(2) However, the effect of overloading can be simulated in other ways (through the arguments array)
function add(){
if(argumnets.length==2){
return argumnets[1]+arguments[2];
}
else
return 0;
}
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).