JavaScript in the Web front end 20180330

Source: Internet
Author: User
Tags function definition mathematical functions object object script tag

First, JavaScript overview

JavaScript is a scripting language based on objects and events.

Characteristics:

1. Security (does not allow direct access to the local hard disk (because it is interpreted by a remote browser), it can do is the dynamic interaction of information

2. Cross-platform (as long as the browser can interpret JS can be executed, the Peace Platform (System) independent), Java is resolved by the virtual machine so it does not need to rely on the platform.

Second, JavaScript is different from Java

1.JS is the product of Netscape company, early Java is the product of sun company

2.JS is Object-based (and the object is already encapsulated) and event-driven, and Java is Object-oriented

3.JS simply explain can be executed (JS in the client, as long as the browser can interpret JS can be executed), Java needs to be compiled into a bytecode file, and then execute

4.JS is a weak type (non-rigorous, even do not write semicolons can, specification or write), Java is a strong type (rigorous).

For example, Java defines 8 types of data (5 basic, 3 references), and JS has no data type at all

For annotations, JS also uses/**/and//

Iii. how JavaScript and HTML are combined

You want to incorporate other code into your HTML, all in the form of a label. The script tag can be stored anywhere on the page, either in the head, in the body, or between the head body, or outside the head body.

1.js code stored in the label to <script type= "TEXT/JAVASCRIPT> </script> in

2. Use the SRC attribute of the script tag to introduce a JS file. (Convenient post-maintenance, expansion, independent to improve the reuse and encapsulation, convenient multiple page reference)

Example: <script src= "Test.js" type= "Text/javascript" ></script>

Note: The type attribute must be added to the script tag in the specification.

Iv. Grammar

Alert ("123");//This is provided by the win system, can be placed directly in JS, the effect is to pop up a dialog box.

The basic elements of a programming language are: variables, statements, functions, data structures (arrays, etc.), similar to high-level languages, manipulating data Objects (IO), manipulating network objects (sockets), etc.

1. Variables

Define variables using the keyword VAR, which is a weak type without specifying a specific data type

Cases:

var x=3;

x= "ABC";//or x= ' abc ' can also, that is, JS inside is a string, no character concept, so single double quotes can be

alert (x);//Results show ABC

var y;

alert (y);//Results show undefined

Note that the special constant value in JS: Undefined, is used when the variable is not initialized, and the value of the variable is undefined, similar to null in Java.

Note that because there is no concept of type in JS, there is no type conversion involved in the operation, such as: The result of 3250/1000*1000,js is 3250, not 3000.

2. Statement (same as Java statement format)

1). Judgment result (if statement)

Note: Var x=3;

if (x==4)//can perform comparison operations

if (x=4)//can be assigned to the operation, and can also be judged, no error

Because 0 is false in JS, not 0 is true (usually 1). That is, empty is false, non-empty is true

So the IF (x==4) result is true;

2). Select result (switch statement)

Note that after the case of JS, it can be a string

3). Loop structure (while statement, do: While statement, for statement).

Cases:

for (Var x=0;x<3;x++)

{

Alert ("x=" +x);

}

var sum= "";

for (Var x=1;x<=4;x++)

{

if (x==4)

sum=sum+ "x=" +x;//connection string

Else

sum=sum+ "x=" +x+ ",";

}

alert (sum);

Ways to write to the page:

document.write ("<font color= ' Red ' >" +sum+ "</font>"), parts of//html are enclosed in quotation marks, not in JS

Note that the difference is that there is no specific data type limitation, so be careful when using it.

Note that when JS error occurs, a yellow exclamation point appears in the status bar of the webpage, and when clicked, there is a hint of what went wrong.

Note that JS in the expression, logic and use &&

Display a 99 multiplication table in tabular form:

Table,table td{

border: #0000ff double 1px;

width:600px;

}

document.write ("<table>");

for (var x=1; x<=9; x + +) {

document.write ("<tr>");

for (var Y=1; y<=x; y++) {

document.write ("<td>" +y+ "*" +x+ "=" +y*x+ "</td>");

}

document.write ("</tr>");

}

document.write ("</table>");

3. Arrays

Easy to manipulate multi-element containers, you can number the elements therein.

Features: can save any element, the length is variable

Format:

var arr =new Array ();//new you can fill the array with elements at any time.

Arr[0] = "Hello";

ARR[1] = 123;

var arr =[4,1,6,8];

arr[6]=100;//This will change the length of the array, the length to 7, the middle of the undefined part is undefined

var arr = {' Hello ', 123,true, ' abc '};

can store any type of data, but the specification is best or the same type, easy to operate.

Basic operations on arrays by traversal

for (Var x=0;x<arr.length;x++)

{

Alert (arr[x]);

}

4. Functions

Because there is no data type, the return type is not involved, as well as the parameter type.

1). General functions

Format (general function definition Mode):

Function name (formal parameter ...)

{

Execute the statement;

(return value;)

}

Code:

function add (x, y) {

return x+y;

}

var sum = Add (4,5);

Note that JS also has global variables and local variables, which are used in the same way as Java.

Note that JS does not have overloaded form, define two parameters, pass one is not wrong, as follows:

Fuction Show (x, y)

{

Alert (x+ ', ' +y);

}

Show (3);//Results show 3,undefined

At the same time, because of this, when the definition of the parameter is less, but the incoming more, it will not be wrong, but also receive, receive a array named arguments, (this array each function has, do not need to define manually)

Cases:

Fuction Show ()

{

for (Var x=0;x<arguments.length;x++)

Alert (arguments[x]);

}

Show (3,4,5,7);//Results show 3,4,5,7

Although it is possible to do so, in terms of specification, what is required is defined on the parameters so that the reading is good.

Note that the function itself is an object in JS, the function name is the name of the object, the function name points to the function object, so:

var x=show;//this does not call the Show method, but rather means that X points to a function object pointed to by show

alert (x);//This will print out the entire function content

2). Dynamic functions

JS has built-in function object functions

So defining a function can be like defining the form of an object:

var function name = new function ("parameter", "parameter",..., "function internal code");

Cases:

var show = new Function ("X", "Y", "var sum=x+y;return sum;");

var sum = Show (5,2);

Characteristics:

When defined, both parameters and function bodies can be passed in as variables.

That is, dynamic functions, parameters, and function bodies can be passed by parameters and can be specified dynamically.

Dynamic functions are relatively rare.

3). anonymous function

Define and use the format:

var variable name = function ()

{

}

Variable name ();

JS is also event-driven, so anonymous functions can often be used as a way of handling events. Therefore, it is more common to define the behavior of event properties.

Cases:

The window's data is loaded with an onload event, which can be directly equal to an anonymous function, so that the event can be handled by an anonymous function.

That

Window.onload = function ()

The {///anonymous function is like an anonymous object, so you can assign a value

Alert ("onload over");

}

This is a simplified notation, or it can be written like this:

Fuction method ()

{

Alert ("onload over");

}

Window.onload = method;//is not a return value all cannot have parentheses, assign value with Object

5. Objects

JS does not have a class keyword, JS is the form of functions to create objects out. That is, JS can also customize the object in addition to the built-in objects (such as the Document object) already provided

Cases:

function person ()

{//similar constructors

Alert ("Person inti");

}

var p = new person ();//defines a person object, at which point the constructor person () is called

P.name = "133";//define (Increase) the properties of the person object

P.age =22;//defining member variables

p.eat= function ()

{//define (increase) the behavior of the person object, define member functions

Alert ("Eat");

}

P.eat ();//The function in the object is called.

Note that the property can also be added and initialized in the constructor:

function person (name,age)

{//similar constructors

This.name=name;

This.age=age;

}

var p= new person ("Lisi", 90);//Incoming initialization value when instantiating an object

alert (p.name);

Alert (p["name"]);//This is also possible, the effect is the same as before, the advantage of this approach is that it can pass parameters in the past P

Note that the object is the p above can be individually encapsulated into a JS file, other pages can be referenced by the file, you can access the object is the P object. This allows the implementation of a JS file to be used by multiple pages, eliminating the repetitive code.

Note that if in the page referencing the JS file, new has the same object as the class of the object in the JS file, the object can only access the properties in the class, and cannot access the object in JS, even if the two object names are the same (nearest principle).

JS is used to manipulate the object's statement:

1). With statement

Format:

With (object)

{//any properties and methods of this object can be directly used in this area

}

Apply: When calling multiple members of an object, in order to simplify the call, encode "object." Repeated writing in this format.

Or, the range used to confirm the function of an object.

Cases:

function person (name,age)

{//similar constructors

This.name=name;

This.age=age;

}

var p= new person ("Lisi", 90);//Incoming initialization value when instantiating an object

With (p)

{

alert (name,age);

}

2). for (...) Statement

Used to iterate over an object or array

Cases:

To traverse an object:

function person (name,age)

{//similar constructors

This.name=name;

This.age=age;

}

var p= new person ("Lisi", 90);//Incoming initialization value when instantiating an object

for (s in P)

{

Alert (s+ ":" +p[s]),//s is the property name, P[s] is the corresponding property value, because P does not have an S property, so you cannot use Stu.s

}

To iterate over an array:

var arr={5,1,2,3};

for (x in arr)

{

Alert (arr[x]);//x is the subscript of an array.

}

6.js built-in objects (existing objects)

View the built-in objects to view the JS manual.

For example, the object object, when new is passed in the value can also define objects, but this method is seldom used

1). String Object

A string object is typically created without new, directly var str= "", which means that a string object can be created using the strings text display.

You can view the manual for the properties and methods of the object.

Where the Bold method adds a B tag to the string,

FontColor adds color to the string in HTML,

The link method turns the current string into a hyperlink

The substring method takes the start and end bits, and does not contain the end bit

Substr method, specifying the length from the start bit, longer than the length of the string, length using string length

The match method, which is used in the regular expression

Code:

var str = "ABCDE";

var y=str.bold ();

document.write (y);

var z=str.fontcolor ("Red");

document.write (z);

alert (z);

var a=str.link ("http://www.baidu.com");

document.write (a);

var i=str.substring (2,4);//result CD, not including fourth

var j=str.substr (2,4);//Results CDE, only three so long, so the length becomes 3, if enough, then cdef

Note When you get the string length, there is no method, only the property

2). Math Object

is an intrinsic object that provides basic mathematical functions and constants.

This means that you can use the properties and methods in the form of.

Format:

Math. [{Attribute | method}]

Like what

The random method, which is used to get the stochastic number.

Code:

var d =math.random () *10+1;

3). Global Object

Some common methods are encapsulated in this object, which is an intrinsic object, which can be used directly, but this direct use is not required to write global, directly write its internal properties and methods on the line.

Like what

The parseint method, when the string in its argument is not a string, will return Nan, as to determine the return value can be used in the isNaN method,

Cases:

parseint ("abc")//Return Nan

parseint ("12ABC")//Return 12

As in the last random number, you can use this method to take the whole

Note that the parseint can also pass in the cardinality parameter, indicating which binary to parse,

Cases:

var num=parseint ("110", 2);//result num equals 6

Similar to parseint and the way to convert numbers to strings ToString, but the method is a fixed method (global method) is not in the global object, you can directly use (each variable has a method),

Cases:

var x=6;

var num =x.tostring (2);//Result num= "110", 2 is radix, note cannot be written directly 6.toString

//

4). Date Object

The methods within the object can be obtained either by date or by the object, and the object returned by new is also a string.

Cases:

var d = new Date ();

alert (d);//display date information directly

With (d)

{

var month= (Getmouth () +1);

month = (mouth>9) month; " 0 "+mount;//Month less than 9 pieced together into a two-bit display

Alert (getYear () + "year" +mouth+ "month" +getdate () + "Day Week" +getday ());

}

5). All built-in objects have prototype properties

Returns a reference to the object type prototype, that is, a reference to the object that is used to add new properties and methods to the object by returning the object reference.

Code:

function Getmax ()

{

var max = this[0];

for (Var i=0;x<this.length;x++)

{

if (This[x]>max)

MAX=THIS[X];

}

return Max;

}

Array.prototype.getZuiDa =getmax;//getmax is a well-defined method, which adds a new method to the array object named Getzuida

var arr={1,23,8,9};

var x=arr.getzuida ();//Because the new method is added earlier, the defined array object can use the newly added method

alert (x);

Arr.sort ();//Sort

For (y in arr)

{

Alert (Arr[y]);

}

JavaScript in the Web front end 20180330

Related Article

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.