JS (ii) object

Source: Internet
Author: User
Tags array sort natural logarithm pow setinterval square root

Brief introduction:

Data types other than null and undefined are defined as objects in JavaScript, and variables can be defined using the method of creating objects, String, Math, Array, Date, RegExp are important built-in objects in JavaScript, and most of the functionality in JavaScript programs is based on object implementations.

<script language= "javascript" >var Aa=number.max_value; Use a numeric object to get the maximum number of Var bb=new String ("Hello JavaScript"); Create a String object var cc=new date ();//Create Date object var dd=new Array ("Monday", "Tuesday", "Wednesday", "Thursday"); Array Objects </script>

3.1 String ObjectString Object creation

String creation (two ways)
① variable = "string"
② String Object name = new String (string)

12 varstr1="hello world";var str1= newString("hello word");
properties and functions for string objects
X.length----get the length of the string X.tolowercase ()---to lowercase x.touppercase ()----to uppercase
X.trim ()------------String Query method X.charat (Index)----str1.charat (index); The character index to get X.indexof (findstr,index)---query string position x.lastindexof (findstr) x.match (regexp)----match returns an array of matching strings, if no match is returned Nullx.search (regexp)----search returns the first character position index of the matching string example: var str1= "Welcome To the world of js! "; var str2=str1.match ("World"); var str3=str1.search ("World"); Alert (str2[0]); The result is "world" alert (STR3); The result is 15----substring processing method x.substr (start, length)----start represents the start position, length indicates the Intercept length x.substring (start, end)-- --end is the end position x.slice (start, end)----the slice operation string Example: Var str1= "ABCDEFGH"; var str2=str1.slice (2,4); var str3=str1.slice (4); var str4=str1.slice (2,-1); var str5=str1.slice ( -3,-1); alert (STR2); The result is "CD" Alert (STR3); The result is "EFGH" alert (STR4); The result is "CDEFG" alert (STR5); The result is "FG" X.replace (FINDSTR,TOSTR)---string substitution x.split (); -----split string var str1= "One, two, three, four, five, six, day"; var strarray=str1.split (","); Alert (strarray[1]);//result is "two" X.concat (ADDSTR)-----stitching string
3.2 Array Object3.2.1 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:

View Code3.2.2 Properties and methods for array objects

Join method:

View Code

Concat Method:

View Code

Array sort-reverse Sort:

View Code

Array slicing operations:

View Code

To delete a sub-array:

View Code

The push and pop of the array:

View Code

The shift and Unshift of the array:

View Code

Summarize the array features of JS:

View Code3.3 Date Object3.3.1 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:

View Codemethod of Date Object-set date and timeView Codemethod of the Date object-conversion of date and timeView Code3.4 Math 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.
3.5 Function Object (emphasis) definition of the 3.5.1 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:

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:

View Code 3.5.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)
invocation of 3.5.3 FunctionView Code 3.5.4The built-in object for the function argumentsView Code 3.5.4anonymous functionsView CodeBack to TopBOM 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

View Code

Example:

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:

View CodeBack to TopDOM ObjectWhat 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 nodenode 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”)
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!

Node operations

To create a node:

1 createElement(标签名) :创建一个指定名称的元素。

Example: Var tag=document.createelement ("Input")
Tag.setattribute (' type ', ' text ');

To add a node:

12345 追加一个子节点(作为最后的子节点)somenode.appendChild(newnode)把增加的节点放到某个节点的前边somenode.insertBefore(newnode,某个节点);

To delete a node:

1 removeChild():获得要删除的元素,通过父元素调用删除

Replace node:

1 somenode.replaceChild(newnode, 某个节点);

Node Property operations:

1. Get the value of the text node: InnerText InnerHTML

2. Attribute operation

     Elementnode.setattribute (Name,value)         Elementnode.getattribute (attribute name)        <--------------> Elementnode. Attribute name (DHTML)     elementnode.removeattribute ("attribute name");

3. Value gets the currently selected value
1.input
2.select (SelectedIndex)
3.textarea
4, InnerHTML add HTML code to the node:
This method is not a standard, but the mainstream browser supports
tag.innerhtml = "<p> to display content </p>";

5, about the operation of class:

123 elementNode.classNameelementNode.classList.addelementNode.classList.remove

6. Change CSS style:

123 <p id="p2">Hello world!</p>document.getElementById("p2").style.color="blue";                             .style.fontSize=48px
DOM Event (Event) events type
OnClick an        event handle that is invoked when a user taps an object. OnDblClick an     event handle that is called when the user double-clicks an object. The onfocus        element gets the focus.               Exercise: The input box onblur         element loses focus.               scenario: For form validation, when a user leaves an input box, the Representative has already entered it and we can verify it.       the contents of the onchange domain are changed.             scenario: Typically used for form elements, which are triggered when the element content is changed. (three-level linkage) onkeydown      a keyboard key is pressed.          Application Scenario: When the user presses the ENTER key in the last input box, the form submits. onkeypress     a keyboard key is pressed and released. onkeyup        a keyboard key is released.
OnLoad a page or an image to finish loading.
onmousedown the mouse button is pressed. OnMouseMove Mouse is moved. onmouseout the mouse to move away from an element. onmouseover mouse moves over an element. OnMouseLeave mouse away from element onselect text is selected. OnSubmit confirm button is clicked.
Bind event Mode

Mode 1:

<div id= "div" onclick= "foo (this)" > Dot me </div><script>    function foo (self) {           //parameter cannot be this;        Console.log ("Point your uncle!");        Console.log (self);       } </script>

Mode 2:

<p id= "abc" > Try!</p><script>    var ele=document.getelementbyid ("abc");    Ele.onclick=function () {        console.log ("OK");        Console.log (this);    This is used directly with    };</script>
Event description

1.onload:

The OnLoad property is only added to the BODY element in development. The triggering of this attribute indicates that the page content is loaded. Application scenario: When something we want to execute immediately after the page is loaded, you can use the event property.

View Code

2,onsubmit:

Triggered when the form is submitted. This property can also be used only for form elements. Scenario: Verify that the user input is correct before the form is submitted. If validation fails. In this method we should block the submission of the form.

View Code

3. Event Propagation:

View Code

4, Onselect:

View Code

5, OnChange:

View Code

6, OnKeyDown:

Event object: The Event object represents the state of the incident, such as the element in which the event occurred, the state of the keyboard key, the position of the mouse, and the state of the mouse button.
Events are often used in conjunction with functions, and functions are not executed until the event occurs! The event object is created as soon as it occurs, and is passed to the event function when the event function is called. We just need to receive it. For example, onkeydown, we want to know which key is pressed and need to ask the property of the event object, here is the keycode.

View Code

7. The difference between onmouseout and OnMouseLeave events:

View Code

JS (ii) object

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.