Rupeng net learning notes (9) JavaScript, learning notes javascript

Source: Internet
Author: User

Rupeng net learning notes (9) JavaScript, learning notes javascript

JavaScript notes

1. Introduction to JavaScript
1. JavaScript is a computer programming language that defines variables and executes loops like other programming languages.

2. JavaScript code is mainly executed on the browser to provide dynamic results for HTML pages.

3. JavaScript is a scripting language. Its Code is interpreted and executed, that is, the code will be executed after an explanation of the Code.

4. JavaScript can be abbreviated as js

Ii. js variable Declaration

1. js is a weak type language. The weak type does not mean that the data itself has no type, but that the variable has no type.
For example, if a variable is a, the value of a can be either a string or a numerical value.

2. js uses the keyword var to declare the variable: var a; or var a = 1.2; or var a, B, c;

3. Due to the weak type of js, we can write the code as follows:
Var a = 1.2;
A = "hello ";

4. Remember: js does not contain int a = 1.

Iii. js Data Types

1. js defines data types in 6, of which 5 are original types:
Boolean, Number, String, Null, Undefined, and an Object type

Boolean: true, false

Number: the real Number between-(253-1) and 253-1, plus two special values: Infinity and NaN.

String: Any Character Sequence enclosed by a pair of double quotes or single quotes, such as "abc"

Null: null

Undefined: undefined

Object: the Object type value is called an Object (for details later)

2. The value of the original type cannot be changed. For example, var a = 1.2; although a can be re-assigned, the value 1.2 itself cannot be changed (constant)

3. The Object type value can be changed,
For example, var obj = new Object (); we can use obj. name = "egg"; this syntax adds data to an Object, that is, the data inside the Object can be changed.


Iv. Operators and expressions

1. js also provides a set of operators similar to other programming languages

Arithmetic Operator: +-*/% (+ -- + =-= * =/= % =)

Comparison OPERATOR: >>=<====! =! =

Logical OPERATOR: | &&!

Bitwise OPERATOR: | &~ <>>>> (Learn more)

String connector: +

Others: typeof instanceof new


The operator priority is similar to that of other programming languages.

2. expression: It is composed of operators and operands. An expression must have a result after calculation. Special expressions, such as object creation and function calling, all belong to the expression.



5. Compare the two operands to be equal

1. js has two equal comparison methods: Standard Comparison (=) and strict comparison (=)

Strict comparison: if the values and Data Types of the two operands are the same, the comparison result is true.
1 = 1 result true
1 = "1" result false

Standard Comparison: convert two operands to values of the same data type before strict comparison.
1 = 1 result true
1 = "1" result true

Conversion rules: (the conversion of all six data types is complex. Only two common conversions are listed)
When Boolean and Number are compared, true is converted to 1, false is converted to 0
When comparing String and Number, String is converted to the corresponding value.

6. typeof Operator

1. typeof is used to obtain the data type of the operand. type descriptions in string form are returned. For example, if typeof 1.2 is set to "number"
Type result (string type)
Undefinedundefined
Nullnull
Booleanboolean
Numbernumber
Stringstring
Functionfunction
Any other object

Typeof null is somewhat special. The result is an object.

VII. instanceof Operator

1. instanceof is used to determine whether an object is a class object.

Var obj = new Object ();
Obj instanceof Object returns true

2. Note: The first operator here is an object, not a value of the original type.


8. new operator

1. new is used to create an Object: var obj = new Object ();

2. js also provides a String class, var str = new String ("abc ");

3. Although the object of the String class is also a String, it is different from that of the original type.

Var str1 = "abc"; // The value of str1 is of the original type.
Var str2 = new String ("abc"); // The value of str2 is the object
Str1 = str2 // The result is true.
Str1 = str2 // The result is false.
Typeof str1 // result string
Typeof str2 // result object
Str1 instanceof String // The result is false.
Str2 instanceof String // The result is true.

Therefore, try not to use new to create a String object.

Note: new Xxx (); can be abbreviated as new Xxx;


9. keywords and reserved words

1. js keywords: words that have special meanings used by js

Break, case, class, catch, const, continue, debugger, default, delete, do, else,
Export, extends, finally, for, function, if, import, in, instanceof, let, new, return,
Super, switch, this, throw, try, typeof, var, void, while, with, yield


2. Reserved js words: words that may be used by js for specific purposes in the future

Enum, await, implements, package, protected, static, interface, private, public, abstract,
Boolean, byte, char, double, final, float, goto, int, long, native, short, synchronized, transient, volatile

10. control statements

Most of the js process control statements are familiar to us.
If else
Switch
While
Do while
For
For in
Break
Continue
Return

11. js pre-defined classes and pre-defined objects

1. js has pre-defined some classes and objects for our use.

Predefine class:
Object, Number, String, Boolean, Null, Undefined, Array, Function, Date, Math, RegExp, etc.

Predefined object:
Arguments array objects, and some global function objects such as parseFloat (), parseInt (), eval (), isNaN (), isFinite (), etc.


2. JavaScript is an object-based programming language, but it is not a typical object-oriented programming language.
Because we don't want to learn the underlying implementation mechanism of js, we only need to know this.


12. Object Class

1. objects are the most basic classes in js and are used to create common objects. These objects are usually used to store data.

2. Creation method:
Var obj = new Object ();

Add attribute (data): obj. name = "egg ";

Get the property value: var name = obj. name; // obj ["name"]

Traversal property:
For (var key in obj ){
Var value = obj [key]
}


3. There is another way to create an object:

Var obj = {};
Var obj2 = {"name": "egg", "age": 24 };

This method becomes: JSON (JavaScript Object Notation), that is, js represents an Object.

JSON-format data can be directly recognized as js objects by js, because js represents the object in the memory.

JSON format Syntax:

An object is represented by a pair of braces ({}).
The object can contain several key-value pairs. The key must be of the String type, and the where can be of any type.
In some non-strict writing methods, double quotation marks or single quotation marks of the key can be omitted twice, but this is not recommended.
A key-value Pair uses a colon to separate keys and values, and different key-value pairs are separated by commas.
In particular, an array object is represented by a pair of [] brackets. The array element can be of any type.


13. Array class
Var arr = ["egg", "Jianguo", "laibao"];

Array objects Support index operations: accessing elements through arr [index]

The array has a length attribute, indicating the number of elements (in fact, the length value is the maximum index value + 1)

We recommend that you use for loop to traverse array elements:
For (var I = 0; I <arr. length; I ++ ){
Var element = arr [I];
}


The Array class also provides many methods to operate elements:

Add elements at the end of push () (the number of elements in the array can be dynamically changed)

Unshift () adds an element at the beginning

Pop () deletes the End Element

Shift () deletes the starting Element

Note: arrays also support the set of operations for common objects, but it is not recommended to do so.

Iv. function

1. A function is the first object in js. It not only has constructor and attribute of common objects, but also can be called.

2. A function is usually used to complete a specific action and can be called repeatedly, similar to the methods in object-oriented programming languages.

3. In view of the important position of functions in js, js provides multiple syntaxes to declare and use functions.

In fact, declaring a Function is an object that creates a js Function class.




15. function declaration method

Statement Syntax:
Function Name (parameter list ){
Function body
}
Call Syntax: function object ();

 

Sample Code:
Function sum (n1, n2 ){
Var sum = n1 + n2;
Return sum;
}

Sum ();


Function Name: it consists of letters, numbers, underscores, or $, and cannot start with a number.

Parameter List: parameters to be received by the function. Because js is a weak type language, the parameter list in the Declaration syntax ignores var.

Function body: js Code that meets specific requirements.

Return Value Type: The Declaration syntax does not include the return value type, but the function can use the return statement in the function body to return any type of value. If no return statement exists, undefined is returned by default.

The js engine in the browser parses and manages the functions declared using this method before executing the js Code. So you can call this function before it is declared.

Note:

Js does not have the concept of function overloading. in multiple functions with the same name, no matter whether the number and name of parameters are the same, the declared


16. arguments array object in the function

In the function body, you can directly use the arguments array object. The elements of this array are all the parameters actually passed in when this function is called.

The actual number of parameters passed in when a function is called can be different from the number of parameters passed in when a function is declared. Inputting different types of parameters will also cause the results to be inconsistent with expectations.

Because js functions have flexible return values, number of parameters, and parameter types, we should ensure that the expected parameters of the input function are called.

Function sum (n1, n2 ){
Var sum = n1 + n2;
Return sum;
}

Function sum2 (n1, n2 ){
Var sum = 0;
For (var I = 0; I <arguments. length; I ++ ){
Sum + = arguments [I];
}
Return sum;
}


17. function declaration Method 2: anonymous Function

Var variable name = function (parameter list ){
Function body
}

Var sum = function (n1, n2 ){
Var sum = n1 + n2;
Return sum;
}

Sum (1, 2); // call this function


1. This method is also called an anonymous function. The js engine does not parse and manage anonymous functions in advance. Therefore, anonymous functions cannot be called in advance and do not have to be overwritten.

2. In particular, if the variable name is omitted, you can create a one-time function that will be called immediately after declaration:
(Function (n1, n2 ){
Var sum = n1 + n2;
Return sum;
}) (1, 2 );
// Enclose the entire function with parentheses as the function name, followed by input parameters, which is equivalent to directly calling


18. function declaration method 3. Original declaration method

Var variable name = new Function (parameter list, Function body); // The parameter list and Function body must both be strings

Var sum = new Function ("n1", "n2", "var sum = n1 + n2; return sum ");

Sum (1, 2); // call this function

This is the most primitive declaration method, but the readability is very poor. Just understand it.

Since a Function is a Function object, a Function can assign values to a variable,
You can also assign values to attributes of another object,
Function sum (n1, n2) {return n1 + n2 ;}
Var xx = sum; // assign the sum function to the variable xx
Xx (); // call the sum function

Var obj = {};
Obj. xxx = sum; // assign the sum function to the xxx attribute of the obj object.
Obj. xxx (); // call the sum function

19. js variable scope

1. the variables directly defined in the <script> label are global variables, which are valid for all js Code on the page.

2. js pre-defines some global variables, such as name. Pay attention to this during testing.

3. Before the js engine executes the code, it will place all the global variable declarations on the top, and the position of the value assignment statement remains unchanged.

4. variables declared in statements such as if and loop are promoted to global variables as long as they have been declared.

5. The variable can be declared repeatedly and overwritten. The variable value is the value previously declared.

6. the variables defined in the function are local variables, and the local variables are not upgraded to global variables, so they are not accessible outside.

7. In two nested functions, variables defined by the outer function are valid for the inner function, and vice versa.

8. The variables defined in two functions that are not nested functions are invalid for each other.

9. Pay special attention to the use of nested function variables.


Function (){
Var I = 0;
Var B = function (){
// The function body code is not executed when the function is declared.
Var m = I;
Alert (m );
}
I = 10;
B (); // when the function is executed, the function body code var m = I; will be executed, but at this time I is 10;
}

A (); // The result is alert 10

Function (){
Var I = 0;
Var B = function (){
Alert (B. I );
}
B. I = I; // store the I value somewhere before the I value changes
I = 10;
B ();
  
A (); // The result is 0.

 

20. String type

1. Whether it is a String value of the original type or an object of the String class, the following attributes and methods are available.

Length attribute: number of characters in the string

CharAt (number): gets the string at the specified index position

Concat (string) concatenates a string, and the effect is equivalent to + string Connector

IndexOf (string) returns the index location of the specified string for the first time in this string

LastIndexOf (string) returns the last index position of the specified string.

Replace (string1, string2) replace string1 once with string2

Substring (number1, number2) retrieves the sub-string from number1 to number2.

Split (string) splits the string using the specified string and returns the string array after splitting.

Trim () removes spaces at both ends


21. Date

The Date class is used to process the Date and time, based on the number of milliseconds (timestamp) starting from January 1, January 1, 1970 (the World Standard Time)

There are multiple ways to create date objects:
Var now = new Date (); // current time

Var date = new Date (1000); // It took January 1, 1970 milliseconds since January 1, 1000

Var date = new Date (year, month, day, hour, minute, second, millisecond); // create a date object by specifying each time component

Date:
GetTime () is used to obtain the timestamp of the latest Date object.

In addition, a series of getter/setter methods are provided to operate on each time component, such as getHours ()

Note: Except for getMonth (), the returned values start from 0, and the rest start from 1.


22. Math mathematical functions

1. There is a Math in js that can be used to execute mathematical tasks, but it does not have constructor, so it cannot create objects, but it can directly call functions or attributes, similar to static classes in other programming languages

2. Common attributes:
Math. E Euler Constant, also the base number of the natural logarithm, approximately 2.718

Math. LN2 2's natural logarithm, approximately 0.693

Math. PI circumference rate, the ratio of circumference to diameter of a circle, approximately 3.14159

3. Common Methods

Math. abs (x) returns the absolute value of x.

Math. ceil (x) returns the rounded up value of x.

Math. floor (x) returns the largest integer smaller than x.

Math. round (x) returns the integer rounded up.

Math. max (n1, n2...) returns the maximum value from 0 to multiple values.

Math. min (n1, n2. ..) returns the minimum value from 0 to multiple values.

Math. pow (x, y) returns the y Power of x.

Math. random () returns a pseudo-random number between 0 and 1.

Math. sin (x) returns the sine value.

23. RegExp class, Regular Expression

1. Regular Expressions are a set of independent rules. Almost every programming complaint provides classes that implement this set of rules.

2. Create a regular object in two ways:
Var reg = new RegExp (pattern, flags)
Var reg =/pattern/flags
// If the flags value is g, it indicates a full match. If the flags value is I, the case is ignored.

3. RegExp provides two common methods:
Test () to test whether the text at one end matches the Regular Expression
Exec () is used to obtain the regular expression matching part of a text segment (the returned value is an array or null)

4. elements and attributes of the array returned by the exec () method

Attribute/index Description Example
[0] matching string w
The index-matched characters are located at the index location of the original string.
Input original string hello world


Twenty-four. js top-level object: window object

1. In JavaScript, both global variables and functions are stored in the properties of the window object.

2. The window object indicates the entire browser window, not only js content, but also the entire HTML page (including all elements and CSS content) under the management of the window object.

3. Each time a browser opens a tab, a window object is created. Sometimes multiple pages are opened in a browser window, that is, multiple window objects are displayed. Each window object has almost no influence on each other.

4. In addition, the window object provides other global objects.


25. Global Properties of window

1. location address bar object
Href attributes
Reload ()
The distance between the left border of the screenX browser and the left border of the screen
The distance between the Right Border of the screenY browser and the right border of the display screen
Document Object on the document page, indicating an html page


26. Global functions of window

Alert () // a prompt box is displayed.

Confirm () // a confirmation box is displayed.

Prompt () // the pop-up input box

Close () // close the current page

Open () // open a new tag

SetInterval (), clearInterval ()

SetTimeout () // call a function or computing expression, clearTimeout () after the specified number of milliseconds ()


27. JavaScript debugging

1. JavaScript code execution has the following features: explain an execution sentence from the top down and stop execution when an error occurs.

2. js Code debugging steps:
Press F12 to open the debugging Interface
Select Sources
Click the page to debug
Refresh page (add breakpoint page as needed)


28th, introduce external js files

JavaScript code can be extracted and introduced in this way:
<Script type = "text/javascript" src = "test. js"> </script>

JavaScript code cannot be written in the <script> label of an external js file, which is ignored or in the form of a single tag.




















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.