JS of the front end (ii)

Source: Internet
Author: User
Tags array sort getdate time zones local time natural logarithm

Array Object1 Array Creation

There are three ways to create an array:

Creation method 1:var Arrname = [element 0, Element 1,....];          var arr=[1,2,3]; creation method 2:var arrname = new Array (element 0, Element 1,....); var test=new array ("A", "true"), creation mode 3:var arrname = new Array (length);  Initialize Array object:                var cnweek=new array (7);                    Cnweek[0]= "Sunday";                    Cnweek[1]= "Monday";                    ...                    Cnweek[6]= "Saturday";

To create a two-dimensional array:

var cnweek=new array (7); for (Var i=0;i<=6;i++) {    cnweek[i]=new array (2);} Cnweek[0][0]= "Sunday", cnweek[0][1]= "Sunday", cnweek[1][0]= "Monday"; cnweek[1][1]= "Monday"; cnweek[6][0]= "Saturday"; cnweek [6] [1]= "Saturday";
View Code2 properties and methods for array objects

Join method:

X.join (BYSTR)----       splicing array elements into string                            var arr1=[1, 2, 3, 4, 5, 6, 7];                var str1=arr1.join ("-");                alert (STR1);  
View Code

Concat Method:

X.concat (value,...)    ----                    var a = [n/a];                  var b=a.concat (4,5);                  Alert (a.tostring ());  The returned result is a                              b.tostring ().  Returns the result as 1,2,3,4,5
View Code

Array sort-reverse Sort:

X.reverse ()//x.sort () var arr1=[32, N, 111, 444];//var arr1=["a", "D", "F", "C"];arr1.reverse (); Reverses the array element alert (arr1.tostring ());//The result is 444,111,12,32arr1.sort ();    Sort array Element alert (arr1.tostring ());//result for 111,12,32,444//------------------------------Arr=[1,5,2,100];//arr.sort () //alert (arr);//If you want to compare by numbers? Function Intsort (A, b) {    if (a>b) {        return 1;//-1    } else if    (a<b) {        RETURN-1;//1    }    else {        return 0    }}arr.sort (intsort), alert (arr), function Intsort (A, b) {return a-a    ;}
View Code

Array slicing operations:

X.slice (start, end)////use annotation////x to represent the array object//start represents the start position index//end is the end position the next array element index number//The first array element index is 0//start, end can be negative,- 1 represents the last array element//end omitted is equivalent to intercept all array elements from the start position after Var arr1=[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' H '];var arr2=arr1.slice (2,4); var Arr3=arr1.slice (4); var arr4=arr1.slice (2,-1); alert (arr2.tostring ());//The result is "c,d" alert (arr3.tostring ());//The result is "e,f, G,h "alert (arr4.tostring ());//The result is" C,d,e,f,g "
View Code

To delete a sub-array:

X. Splice (Start, DeleteCount, value, ...) The primary use of the annotation//x to represent the array object//splice is to delete and insert the specified position in the group//start the start index//deletecount Delete the number of array elements//value represents the array element inserted at the delete location// The value parameter can omit               var a = [1,2,3,4,5,6,7,8];a.splice]; alert (a.tostring ());//a becomes [1,4,5,6,7,8]a.splice]; alert (A.tostring ());//a becomes [1,5,6,7,8]a.splice (1,0,2,3); alert (a.tostring ());//a becomes [1,2,3,5,6,7,8]
View Code

The push and pop of the array:

Push Pop These two methods simulate a stack operation//x.push (value, ...)  Stack//x.pop () stack      //Use annotations////x to represent the array object//value can be any value for string, number, array, etc.//push is to add value to the end of the array x//pop is to remove the last element of the array x var Arr1=[1,2,3];arr1.push (4,5); alert (arr1);//result is "1,2,3,4,5" Arr1.push ([6,7]); alert (ARR1)//result is "1,2,3,4,5,6,7" Arr1.pop (); alert (arr1);//The result is "1,2,3,4,5"
View Code

The shift and Unshift of the array:

X.unshift (Value,...) X.shift ()//Use annotation//x to represent an array object//value can be a string, a number, an array, and any value//unshift is to insert value value into the beginning of the array x//shift is the first element of the array x is removed var arr1=[1,2,3] ; Arr1.unshift (4,5); alert (arr1)  ; The result is "4,5,1,2,3" arr1. Unshift ([6,7]); alert (arr1);  The result is "6,7,4,5,1,2,3" Arr1.shift (); alert (arr1);  The result is "4,5,1,2,3"
View Code

Summarize the array features of JS:

The attribute of an array in  JS         //java, specifies what  type of array it is, and only what type it is. There is only one type.         The array attribute in JS 1:js can be any type, without any restrictions.         The array attribute in JS is 2:js, and the length is changed with the subscript. How long it will take.         var arr5 = [' abc ', 123,1.14,true,null,undefined,new String (' 1213 '), New Function (' A ', ' B ', ' Alert (a+b) ')];  /* alert (arr5.length);//8         arr5[10] = "hahaha";         alert (arr5.length);         alert (arr5[9]);//undefined */
View CodeDate Object1 Creating a Date object
Method 1: Do not specify the parameter var nowd1=new date (); Alert (nowd1.tolocalestring ());//Method 2: The parameter is a date string var nowd2=new date ("2004/3/20 11:12"); Alert (nowd2.tolocalestring ()), Var nowd3=new Date ("04/03/20 11:12"), Alert (nowd3.tolocalestring ());//Method 3: Parameter is the number of milliseconds Var Nowd3=new Date (nowd3.tolocalestring ()); alert (nowd3.toutcstring ());//Method 4: Parameter is month day hour minute second millisecond var nowd4=new Date (2004,2,20,11,12,0,300); alert (nowd4.tolocalestring ());//milliseconds do not show directly
method of the Date object-Gets the date and time
Get the date and time getdate () get the                 Day getday ()                 Get the Week getmonth ()               get the Month (0-11) getfullyear ()            get the full year getyear ()                Gets the year gethours ()               Gets the Hour getminutes () Gets the Minutes getseconds () gets the             seconds getmilliseconds () gets the        milliseconds gettime ()                returns the cumulative number of milliseconds (From 1970/1/1 Midnight)

Example exercises:

var year = Date.getfullyear (); 3.        Get the current month JS in the month is from 0 to 11.        var month = Date.getmonth () +1; 4.        Get current daily var day = Date.getdate (); 5.        Get current hour var hour = date.gethours (); 6.        Get current minute var min = date.getminutes (); 7.        Get current Second var sec = Date.getseconds (); 8. Get current week var week = Date.getday ();  No Getweek//June 18, 2014 15:40:30 Wednesday return year+ "year" +changenum (month) + "monthly" +day+ "Day" +hour+ ":" +min+ ":" +sec+ "    "+parseweek (week);    }alert (Getcurrentdate ());//resolve automatic completion of two-digit number method function Changenum (num) {if (num <) {return "0" +num;    }else{return num;    }}//converts the number 0~6 to Sunday to Saturday function Parseweek (week) {var arr = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; 0 1 2 3 ........ arr[week];} 
View Codemethod of Date Object-set date and time
Set Date and Time//setdate (day_of_month) Set       day//setmonth (month) Set                 month//setfullyear (year)               set Years//sethours (hour)         Set Hour//setminutes (minute) set     minutes//setseconds (second) set     seconds//setmillliseconds (ms)       set MS (0-999)// SetTime (Allms)     sets the cumulative milliseconds (from midnight 1970/1/1)    var x=new Date (); X.setfullyear (1997);    Set the year 1997x.setmonth (7);        Set the monthly 7x.setdate (1);        Set the day 1x.sethours (5);        Set hour 5x.setminutes (n);    Set minute 12x.setseconds (SI);    Set the second 54x.setmilliseconds (n);        Set milliseconds 230document.write (x.tolocalestring () + "<br>");//Return August 1, 1997 5:12 54 sec x.settime (870409430000); Set cumulative number of milliseconds document.write (x.tolocalestring () + "<br>");//Return August 1, 1997 12:23 50 sec
View Codemethod of the Date object-conversion of date and time
Conversion of date and time: getTimezoneOffset (): 8 time zones x15 degrees x4/degrees = 480; Returns the time difference between local and GMT, in minutes toutcstring () returns the international Standard Time string tolocalstring () Returns the local format time string date.parse (x) returns the cumulative number of milliseconds (from midnight 1970/1/1 to local time) DATE.UTC (x) returns the cumulative number of milliseconds (from midnight 1970/1/1 to International time)
View CodeMath Object
The property methods in this object are related to math.   
ABS (x) the absolute value of the return number. EXP (x) returns the exponent of E. Floor (x) is rounded down with a logarithmic. Log (x) returns the natural logarithm of the number (bottom is e). Max (x, y) returns the highest value in X and Y. Min (x, y) returns the lowest value in X and Y. The POW (x, y) returns the Y power of X. Random () returns an arbitrary number between 0 and 1. Round (x) rounds the number to the nearest integer. Sin (x) returns the sine of the number. sqrt (x) returns the square root of the number. Tan (x) returns the tangent of the angle. Method Exercise: //alert (Math.random ());//Get a random number 0~1 does not include 1. Alert (Math.Round (1.5)); Rounding //exercise: Get 1-100 of random integers, including 1 and //var num=math.random (); num=num*10; Num=math.round (num); Alert (num) //============max min========================= /* alert (MATH.MAX);//2 alert (math.min);//1 *// -------------POW-------------------------------- alert (Math.pow (2,4)); /POW calculates parameter 1 of parameter 2 times Square.
Function Object 1 definition of function?
123 function函数名 (参数){?<br>    函数体;    return返回值;}

Function Description:

You can use a variable, a constant, or an expression as a parameter to a function call
Functions are defined by the keyword function
The definition rules for function names are consistent with identifiers and are case sensitive
Return value must use return
The function class can represent any functions defined by the developer.

The syntax for creating functions directly with the function class is as follows:

?
1 var函数名 = newFunction("参数1","参数n","function_body");

Although the second form is somewhat difficult to write because of the relationship of strings, it helps to understand that a function is simply a reference type and behaves the same as a function explicitly created with the functions class.

Example:

function Func1 (name) {    alert (' Hello ' +name);    Return 8}    ret=func1 ("Yuan");    Alert (ret), var func2=new Function ("name", "Alert (\" hello\ "+name);") Func2 ("Egon")
View Code

Note: JS's function load execution is different from Python, it is the whole load will not be executed, so the execution function is placed above or below the function declaration can:

<script>    //f ();--->ok    function f () {        console.log ("Hello")    }    F ()//----->ok</ Script>
View Code 2 Properties of a Function object

As mentioned earlier, functions are reference types, so they also have properties and methods.
For example, the attribute length defined by ECMAScript declares the number of arguments the function expects.

?
1 alert(func1.length)
3 call to Function
function Func1 (A, b) {    alert (a+b);}    (func1);  3    func1 (//3),    func1 (1);    NaN    func1 ();     NaN    //As long as the function name is written, the parameters are not error-filled.------------------------------function A (a, b) {    alert (a+b);}   var a=1;   var b=2;   A (A, b)
View Code 4The built-in object for the function arguments
function Add (A, b) {        console.log (a+b);//3        Console.log (arguments.length);//2        console.log (arguments);// [+]    }    Add (arguments)    ------------------use 1------------------    function Nxadd () {        var result=0;        for (var num in arguments) {            result+=arguments[num]        }        alert (Result)    }    Nxadd (1,2,3,4,5)//     ------------------The usefulness of arguments 2------------------    function f (a,b,c) {        if (arguments.length!=3) {            throw new Error ("function f called with" +arguments.length+ "arguments,but it just need 3 arguments")        }        else {            alert ("success!")        }    }    F (1,2,3,4,5)
View Code 4anonymous functions
anonymous function    var func = function (arg) {        return "Tony";    } Application of anonymous functions    (function () {        alert ("Tony");    }) ()    (function (ARG) {        console.log (ARG);    }) (' 123 ')
View CodeBack to Top BOM Object

Window object

Window objects are supported by all browsers.
Conceptually speaking. An HTML document corresponds to a Window object.
Functionally speaking: Controls the browser window.
Use: The Window object does not need to create objects, directly to use.
Window Object method
Alert ()            displays a warning box with a message and a confirmation button. Confirm ()          displays a dialog box with a message along with a confirmation button and a Cancel button. Prompt ()           displays a dialog box to prompt the user for input. Open ()             opens a new browser window or looks for a named window. Close ()            closes the browser window.
SetInterval () invokes a function or evaluates an expression by the specified period (in milliseconds). Clearinterval () cancels the timeout set by SetInterval (). SetTimeout () invokes a function or evaluates an expression after the specified number of milliseconds. Cleartimeout () cancels the timeout set by the SetTimeout () method. ScrollTo () scrolls the content to the specified coordinates.
Method uses

1. Alert Confirm prompt and open function

    ----------Alert confirm Prompt----------------------------    //alert (' aaa ');            /* var result = confirm ("Are you sure you want to delete?");    alert (result); *    ///prompt Parameter 1: prompt information.   Parameter 2: The default value for the input box. The return value is what the user entered.    var result = prompt ("Please enter a number!", "haha");    alert (result);    Method Explanation:            The//open method opens and a new window and enters the specified URL. Parameter 1: URL.        Call Mode 1            //open ("http://www.baidu.com");        Parameter 1 Nothing is to open a new window.  Parameter 2. Fill in the name of the new window (you can usually not fill in). Parameter 3: Parameters for the newly opened window.            Open (', ', ', ' width=200,resizable=no,height=100 '); Opens a window with a width of 200 high to 100        //close method  closes the current document window.            Close ();
View Code

Example:

 var num = Math.Round (math.random () *100);    function Acceptinput () {//2. Let user input (prompt) and accept user input result var usernum = prompt ("Please enter a number between 0~100!", "0");                3. Compare the user input value to the random number if (IsNaN (+usernum)) {//invalid user input (repeat 2,3 Step) alert ("Please enter a valid number!");            Acceptinput ();                } else if (Usernum > num) {//Big ==> prompts the user to re-enter (repeat 2,3 steps) alert ("You entered the big!");            Acceptinput ();                }else if (Usernum < num) {//small ==> prompts the user to re-enter (repeat 2,3 steps) alert ("You entered the small!");            Acceptinput ();                }else{//Correct the ==> prompt the user to answer correctly, ask the user whether to continue the game (confirm).                var result = confirm ("Congratulations!), do you want to continue the game?");                    if (result) {//IS ==> repeat 123 steps.                    num = Math.Round (math.random () *100);                Acceptinput ();                    }else{//No ==> close the window (Close method).         Close ();       }            }    } 
View Code

2,Setinterval,clearinterval

The SetInterval () method keeps calling functions until Clearinterval () is called or the window is closed. The ID value returned by SetInterval () can be used as a parameter to the Clearinterval () method.

?
12 语法:<br>     setInterval(code,millisec)其中,code为要调用的函数或要执行的代码串。millisec周期性执行或调用 code 之间的时间间隔,以毫秒计。

Example:

<input id= "ID1" type= "text" onclick= "Begin ()" ><button onclick= "End ()" > Stop </button><script>    function ShowTime () {           var nowd2=new Date (). tolocalestring ();           var Temp=document.getelementbyid ("ID1");           temp.value=nowd2;    }    var ID;    Function begin () {        if (id==undefined) {             showTime ();             Id=setinterval (showtime,1000);        }    }    Function End () {        clearinterval (ID);        id=undefined;    } </script>
View CodeBack to Top DOM Object What is HTML DOM
    • HTML Document Object Model
    • HTML DOM defines a standard way to access and manipulate HTML documents
    • HTML DOM renders an HTML document as a tree structure with elements, attributes, and Text (node tree)
DOM Tree

The DOM tree is drawn to show the relationships between the objects in the document and to navigate the objects.

DOM node node Type

Each component in an HTML document is a node.

This is what the DOM provides:
The entire document is a document node
Each HTML tag is an element node
Text that is contained in an HTML element is a text node
Each HTML attribute is an attribute node

Among them, document and element node is the focus.

Node relationships

Nodes in the node tree have hierarchical relationships with each other.
Terms such as the parent, Son (Child), and fellow (sibling) are used to describe these relationships. The parent node has child nodes. Child nodes of a sibling are called siblings (brothers or sisters).

    • In the node tree, the top node is called root (root)
    • Each node has a parent node, except for the root (it has no parent node)
    • A node can have any number of sub-
    • A sibling is a node that has the same parent node

The following image shows part of the node tree and the relationship between nodes:



accessing HTML elements (nodes), accessing HTML elements is equivalent to accessing nodes, and we are able to access HTML elements in different ways.

Node Lookup

directly find Nodes

?
1234 document.getElementById(“idname”) document.getElementsByTagName(“tagname”)document.getElementsByName(“name”)document.getElementsByClassName(“name”)
<div id= "Div1" >    <div class= "Div2" >i am div2</div>    <div name= "Yuan" >i am div2</div >    <div id= "Div3" >i am div2</div> <p>hello    p</p></div><script>   var Div1=document.getelementbyid ("Div1");////support;//   var ele= div1.getelementsbytagname ("P");//   alert ( ELE.LENGTH);////support//   var ele2=div1.getelementsbyclassname ("Div2");//   alert (ele2.length);////not supported//   var Ele3=div1.getelementbyid ("Div3");//   alert (ele3.length)////not supported/   var ele4=div1.getelementsbyname (" Yuan ");//   alert (ele4.length) </script>
Partial Lookup

Note: Design to look for elements, note <script> label location!

Navigation Node Properties

‘‘‘
Parentelement //Parent node Tag element
Children //all sub-tags
Firstelementchild //First child tag element
Lastelementchild //Last child tag element
Nextelementtsibling //Next sibling tag element
Previouselementsibling //previous sibling tag element ' '

Note that there is no way to find all the brother tags in JS!

JS of the front end (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.