Introduction to "JS" Javascript

Source: Internet
Author: User
Tags first string natural logarithm square root

Javascript

This chapter contains a large number of examples and content referencing the JavaScript tutorials from W3cschool **************

Originally already almost finished writing 90% or so, the result accidentally ran a JS, accidentally kill the browser, accidentally did not save the draft t-t everything to start from scratch wrote Orz. All right, write it again!

Overview

JS is a lightweight browser scripting language with good compatibility (almost all browsers) which means that JavaScript scripts can be run from the PC to all browser-capable devices on the smartphone. So JS is the most popular & most commonly used scripting language on the Internet.
JS is favored by the Internet because it can be embedded in HTML files, and can interact with various elements of HTML. In the HTML file Because JS does not have a special compiler or integration of the IDE and other tools, test JS a little trouble, in most of the following examples, in order to see the effect of JS we will temporarily use document.write (...) This JS method, which involves the HTML DOM, means that the Web page to write HTML code, temporarily as the other language of the print statement, to print out the results.

Basic syntax

Comments

JS, like any other language, can be commented in the form of a comment that resembles C or Java. Note content is expressed in the form of a/*comment*/, and a full line of annotations can be made in//comment form.

Statement rules

The browser and other software will interpret the JS statement. JS is an interpreted language in which the interpreter interprets the statement by itself rather than compiling and running it beforehand.

JS statements can be followed by a semicolon. But this is not a grammatical requirement but a lot of programmers ' habit (like I used to write python, I often do not add semicolons.) )。

Needless to say, JS's statement is case-sensitive, not the same case as SQL.

In addition, like C and Java, JS uses curly braces to enclose some statements to form a block of code. These blocks of code are used in functions, loops, and conditional statements.

Like Python, JS can use "\" To break lines of code, that is, with this symbol in the last line of a row, explaining the current line of code will follow this line to explain.

In the JS statement, the extra spaces will not be interpreted, as is the case with Python. So in writing, you can properly add some empty Glyd beautification code, such as var = 1 and the var=1 effect is the same.

Variable assignment and initialization

JS has a variety of built-in data types, including number (including the traditional int, float type, etc.), Boolean (True and False), string (double or single quotation marks can represent a string), null (null value), array (array), Object (Objects)

Variable declaration with the var keyword, declaration without specifically indicating the type of the variable, when the declaration is not assigned value (such as Var x) The value of the default variable is undefined, that is, the variable has no value (note the difference between undefined and null, undefined is that the variable is not assigned value at all, Instead, NULL says that the value of the variable is a null value. JS supports declaring multiple variables and assigning values in one line:

var city = "Beijing"; var count = var  namevar firstname = "Frank", LastName = "Takanashi"

The two types of array and object are somewhat different.

Array is a python-like list that has the following initialization methods:

var cars=New Array ("Audi", "BMW", "Volvo"); var cars=New  Array (); cars[0]= "Audi"; cars[1]= "BMW"; cars[2]= " Volvo "; var cars=["Audi", "BMW", "Volvo";

While object is similar to Python's dict, it can be initialized as follows:

  * As you can see, the key of object does not have to be quoted, which is not the same as Python.

var person={firstname: "Bill", LastName: "Gates", id:5566}; /* can be wrapped at initialization to make the format clearer . */ var person="Bill", LastName  "Gates", id        :  5566};

If you want to empty the value of a variable, you can assign null to the variable. Again, the null value is not the same as undefined, NULL is a null value, and undefined is no value.

When declaring variables, you can use the New keyword + type name if you do not want to assign a value:

var carname=new  String; var x=      new number ; var y=      new  Boolean; var cars=   new  Array; var New Object;

This declares the variable whose value is null

Methods and properties of the object

This object is a generalized object, in JS, like Python, everything is the object, then the object has methods and properties to be called. The method is called with the symbol ".". We can customize the object, JS also has a lot of built-in objects. All in all, the object is a bit like a class, but JS does not have the concept of class, so we use objects to refer to such an entity. Some of the following are some of the things I might say about the class, which is actually talking about the object. More detailed methods and properties for the built-in objects are also described below.

function

function can be defined in JS

function FuncName (para1,para2) {    //some code}

When defining a function, you do not have to specifically indicate the type of the return value, which specifies the return value of the function using the return statement.

JS can declare a variable in a function, and the variable declared in the function is, of course, a local variable inside the function. What is declared outside of a function is generally a global variable.

* When declaring a variable, you can declare it without the VAR keyword, so the declared variable is a global variable by default and can be accessed by the entire file.

  

operator

Most of the operators in JS are consistent with the operators we know in classic programming, and below I have some things I'm not quite familiar with, and I see that it's a bit more special in JS to write about:

Equal-sex operations:

the "= =" in JS is not equal in the classical sense. JS Use = = will compare two objects to do an automatic type conversion, such as 5 = = "5" In JS is true because it will be the number of type 5 into the string type of "5" and the right comparison, the natural comparison of the result is true. On the other hand, if you do not want it to automatically convert the type, you can use "= = =", three equal signs in the JS middle finger exactly equal.

Add and Subtract operations:

Similar to the above mentioned in the same sex, JS will be added to the string and the type automatically converted to a string to add, such as 5 + "5" will not error and get the result "55", 5 + 5 get 10.

Conditional operation:

JS supports ternary conditional operations similar to (condition) value1:value2.

Logical operation:

The logical operation in JS is a classic &&; | | ;! rather than and; or; Not

Common statements

If/else statements

if (Condition 1)  {  true  when executing code  }Elseif (condition 2)  {  True code executed at the   time of the code}else  {  true   }

Switch statement

Switch (n) { case 1:  1 break  ;  Case 2:  2 break  ; default :    Case   code executed at different time in case 2}

For loop

JS can be used in two forms for the loop, the first is to compare the classic Java and C inside the three conditional statements of the FOR loop:

 for (var i=0; i<5; i++)  {  x=x + "The number is" + i + "<br>";  }

You can see that in the first conditional statement we can make a declaration of the variable, and the declared variable can be used in the loop.

The second form is a for/in loop like in Python. However, it is important to note that the for/in loop in JS is very different from the for/in loop in Python. Also do not forget that JS in the for/in is a small parenthesis.

When for/in iterates over an object (like Dict), like in Python, key represents the contents of each key in object:

var person={fname: "John", lname: "Doe", Age:25};  for inch Person )  {  txt=txt + Person[key];  }

When traversing an array with for/in, it is not the same:

var list = ["A", "B", "C"] for in list) {    document.write (List[index])}

The index in this for/in is not the content "a", "B" and "C" of each member of the list, but refers to the index 0,1 and 2 of the list. In other words, JS in the for/in processing an array, is actually to get the length of the array, and then the length from 0 to the last time to assign to index, with such an index into the loop execution of the statement. So when we visit each member of the list, we do not use index but List[index]

While loop

JS has the while loop and the Do/while loop two kinds:

 while (condition)  {  code to execute  }

The executing body of the do/while loop must be executed once:

 Do   {  The code to execute  }while (condition);

  

Both of these, for and while loops can jump out of the loop with break statements in the loop body, and the continue statement skips the loop

Exception handling

JS can be handled in exception processing such as:

Try   {  // Run code here   }catch(err)  {  ///  Handling errors here  }

In the right place, you can throw an exception with a throw statement:

Throw "Some exception message"

Description of Object & built-in object

As stated above, an object is a presence similar to a class in another language. Because JS is all objects, including functions and various complex data structures, it is possible to construct an object as follows. This function is also called an object constructor (a bit like the constructor of a class)

function Person (Firstname,lastname,age,eyecolor) {this. firstname=FirstName; this. lastname=LastName; this. age= age; this. eyecolor=Eyecolor;

function ChangeName (name) {this. lastname=name;} this.changename=changename;
}

The properties and methods of each built-in type object are described in detail below. A method or property directly under that type, whose invocation method is a type name. A property or method name, where the prefix is the name of the type (in fact, the actual invocation). If it is a property or method of an instance of an object of this type, it is used to represent an instance with the first letter of type Object lowercase

Number Type Object

Property:

Number.MAX_VALUE JS can represent the maximum number, approximately 1.7976931348623157 x 10308.

Numebr.min_value JS can be represented by the minimum number

Number.NaN represents a non-numeric object in which the number (...) is called. When initializing an object, the value is returned if it fails.

Number.negative_infinity negative infinity, this value is returned when overflow

Numebr.positive_infinity positive infinity, returns this value when overflow

Method:

N.tostring (R) returns a string of numbers in R notation, such as 2.toString (2) is 10

N.tofixed (p) returns a string of numbers, taking the P-bit after the decimal point

N.valueof () returns a numeric value

String Type Object http://www.w3school.com.cn/jsref/jsref_obj_string.asp

Property:

S.length returns the length of a string

Method: (The method of the string class, you can see the above URL, listed below a few common)

S.indexof (...) Retrieves a string, returns the location of the first string, and finds no return-1

S.split (Sep) splits the string with the Sep delimiter, returning the resulting array. Unlike Python's split, Sep is required, and when Sep writes "", it does not give an error, but instead divides all characters of the string.

S.match (Pattern) retrieves a string that supports the regular expression pattern. The return is not an index but a match to the content, and the pattern can also be a RegExp object. The behavior of match is related to the specific form of pattern (such as with no G attribute), which is described in detail in the following RegExp object. * when writing regular expressions, do not enclose quotes, such as match ("/\d/g") is not matched by your expected number, but should write match (/\d/g), and match the substring to be quoted, such as "Match" ("123").

  The S.search (pattern) Search method is specifically used to make regular matches, and ignores attribute g, regardless of how many matches you have, I only return the first one found. and returns the index is not the content.

S.replace (pattern,replacement) replaces the specified substring or regular match to the content.

In addition, because JS to interact with the browser interface, so the string class also has a series of methods to modify the output string such as bold (), italics (), Strike () (strikethrough output), toLowerCase (), touppercase (), Link () (hyperlink style output), fontSize (size), fontcolor (color), and so on.

Date type Object http://www.w3school.com.cn/jsref/jsref_obj_date.asp

All properties of the date type are encapsulated in the object and are not allowed to be called directly, and can be obtained and set by calling the related method. Many methods are as the name implies, not detailed

Method:

Date () (does not require prefix plus class name or instance) to return the current date object

D.tostring () Returns a time string formatted as Fri Apr 17:18:47 gmt+0800

D.gettime () returns the timestamp (in milliseconds)

D.getdate () return date 1~31

D.getmonth () 0~11

D.getday () 0~6

D.getfullyear () returns four-bit year

D.gethours () 0~23

D.getminutes () 0~59

D.getseconds () 0~59

All of the above get methods have a corresponding set method to set the value of a property of a date type Object

Array type Object http://www.w3school.com.cn/jsref/jsref_obj_array.asp

Property:

A.length returns the length of an array

Method:

A.pop () deletes from the end of the array and returns a value

A.push (...) Add a value to the end of the array ( note, not append oh )

A.shift () deletes from the beginning of the array and returns a value

A.unshift (...) Add one or more values (separated by commas) at the beginning of the array

A.sort () returns a sorted array (note that it is not the same as in Python, it is returned instead of a sort on itself oh, reverse )

A.join ([Sep]) joins the array member with the Sep delimiter, returning the concatenated string. Default with a comma when Sep is not specified

A.reverse () returns an array in reverse

Math Type Object http://www.w3school.com.cn/jsref/jsref_obj_math.asp

The math type was rarely mentioned before, because math is more of a module or library than a type object. Its properties and methods are called directly by the class:

Property:

Math.PI Pi
Math.sqrt2 Radicals 2
Math.sqrt1_2 Radicals 1/2
Natural logarithm of MATH.LN2 2
Natural logarithm of Math.ln10 10

Method:

Math.Abs (x) Seek absolute value

Math.ceil (x) rounds the number x (returns the smallest integer larger than x)

Math.floor (x) rounding to X

Math.max (x, y) returns the largest in X and Y (natural min also has)

Math.random () returns a random real number between 0~1

Math.Round (x) rounding X

MATH.SQRT (x) Seek X-square root

Besides, there's a whole bunch of trigonometric function methods.

RegExp type Object http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp

RegExp is the abbreviation for regular expression, which is regular expressions. As for the regular, I've talked about it before, but this is about the regular expression object. Just like the object returned in Python re.compile.

First, the regular expression in JS, the basic format is/pattern/attribute. Pattern is a regular expression in the same way as Python, for example. (wildcard) {} (number of repetitions) \d (numeric characters), etc. And the back of the attribute is a unique attribute in JS, its options are i,g,m three kinds.

I represents the ignore case, which is the difference between ignoring cases when matching

G means global, by default, the regular expression always matches only to the first one, but after setting the property G, it will match all of them. Please see the description of the specific method below.

M represents multiline, specifically what does not mean to know.

Property:

R.ignorecase determines whether the regular object sets the I attribute, and the following two are similar.

R.global

R.multiline

R.lastindex is related to how the G property is matched, as described below

Method:

REGEXP (Pattern,attribute) Regular object construction method, and String.match method is different, here the pattern should be quoted in quotation marks, attribute is to write "G", "I" this.

R.test (str) matches the regular object to STR and returns true if the content is matched, otherwise false

R.compile ("New pattern", "new Attribute") compiles a regular object, typically used to update an expression or property of a regular object

R.exec (str) Exec method is divided into two cases, the addition of r object does not set the G property, then exec returns an array array,array[0] is the first match to get the content, Array[1],array[2] These are the contents of the corresponding regular expression of the first , two sub-modes, and so on. If the R object is set to the G property, then exec returns the array of content to match (as if the G property is not set). and set R.lastindex to the index position at the end of the current match, and then the next time that exec is called, the match is continued from this lastindex, so it always matches to the tail and returns a null if no match is reached. Reset lastindex to 0. So we can set up a loop manually so that r.exec can output all the matching content in one breath. Like what:

var str = "Visit W3school, W3school is a place to study web technology."  varnew RegExp ("W3SC (. *) Ool", "G"); var result;  while NULL )  {  document.write (result);  document.write ("<br/>");  document.write (patt.lastindex);  document.write ("<br/>"); }/** Results *****w3school,h14w3school,h24 */

Introduction to "JS" Javascript

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.