Like Peng Web study notes (ix) JavaScript

Source: Internet
Author: User
Tags arithmetic operators bitwise operators logical operators natural logarithm

JavaScript notes

First, JavaScript introduction
1,javascript is a computer programming language that defines variables like other programming languages, executes loops, and so on.

2,javascript code is primarily executed on the browser, providing dynamic effects for HTML pages

3, and JavaScript is a scripting language, and its code is interpreted and executed, that is, the code is executed after a sentence is interpreted.

4,javascript can be referred to as JS

Second, JS variable declaration

1,js is a weakly typed language, and a weak type does not mean that the data itself has no type, but that the variable has no type.
The value of a variable a,a can be either a string type or a numeric type

2,JS uses the keyword var to declare a variable: var a, or var a = 1.2, or var a,b,c;

3, because of the weak type of JS features, we can write code like this:
var a = 1.2;
A = "Hello";

4, remember: JS does not have int a = 1;

Third, JS data type

1,JS defines 6 data types, with 5 of the original types:
Boolean,number,string,null,undefined, and an object type

Boolean:true, False

Number:-(253-1) to 253-1 Real, plus Infinity, NaN two special values

String: Any sequence of characters, such as "ABC", that is wrapped using a pair of double quotation marks or single quotation marks

Null:null

undefined:undefined

A value of type Object:object is called an object (detailed later)

2, the value of the original type is immutable, such as var a = 1.2, although a can be re-assigned, but 1.2 the value itself is immutable (constant)

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


Iv. Operators and expressions

1,JS also provides a complete set of operators similar to other programming languages

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

Comparison operators:> >= < <= = = = = =!==

Logical operators: | | &&!

Bitwise operators: | & ~ << >> >>> (Learn)

String connector: +

Others: typeof instanceof New


Operators have the same precedence as other programming languages

2, expression: consists of operators and operands, an expression after the operation must have a result, especially, such as creating objects, calling functions, etc. belong to the expression



V. Comparison of two operands equal

1,js There are two ways to compare equality: standard comparison (= =) and strict comparison (= = =)

Strict comparison: The value of two operands and the data type are all the same, and the result is true
1===1 result True
1=== "1" result false

Standard comparison: First convert two operands to a value of the same data type, and then make a strict comparison
1==1 result True
1== "1" result true

Conversion rules: (The conversion of all six data types is more complex, only the common two types of conversions)
When Boolean and number compare, true converts to 1,false to 0
String is converted to the corresponding numeric value when string and number are compared

VI, typeof operator

1,typeof is used to get the data type of the operand, returning a type description as a string, as the result of TypeOf 1.2 is "number"
Type result (String type)
undefinedundefined
Nullnull
Booleanboolean
Numbernumber
Stringstring
Functionfunction
Any other object

typeof Null is special, the result is object, you know it.

Seven, instanceof operators

1,instanceof used to determine whether an object is an object of a class

var obj = new Object ();
obj instanceof Object result is true

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


Eight, new operator

1,new is used to create objects: 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 differs from the original type of string

var str1 = "abc"; The value of the STR1 is the value of the original type
var str2 = new String ("abc"); The value of//STR2 is the object
STR1 = = STR2//Result True
str1 = = = STR2//Result false
typeof str1//result string
typeof str2//Result Object
STR1 instanceof String//Result false
STR2 instanceof String//Result True

So try not to create a string object with new

Note: New xxx (), can be abbreviated to new XXX;


Ix. keywords and reserved words

1.js keyword: JS has been used in the use of the word contains a special meaning

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,JS reserved word: JS may use its word for a specific purpose 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

X. CONTROL statements

JS's Process Control statements are mostly familiar to us
If Else
Switch
While
Do While
For
For in
Break
Continue
Return

Pre-defined classes and predefined objects for Xi. JS

1,JS has pre-defined classes and objects for our use.

Pre-defined classes:
Object, number, String, Boolean, Null, Undefined, Array, Function, Date, Math, REGEXP, and so on

Pre-defined objects:
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 not a typical object-oriented programming language.
Since we do not learn JS's underlying implementation mechanism, just need to know this is possible


12. Object class

1,object is the most basic class of JS, used to create ordinary objects, often using these objects to store data

2, create the way:
var obj = new Object ();

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

Get property value: var name = Obj.name; obj["Name"]

Traverse Properties:
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 approach becomes: JSON (JavaScript object Notation) that is how JS represents an object

The data in JSON format can be directly recognized as JS object by JS, because JS is the object in memory.

JSON format syntax:

An object is represented by a pair of {} curly braces
An object can contain several key-value pairs of data, a key must be a string-type value, where can be any type of value
In some of the non-strict wording, you can omit the key two times double quotation marks or single quotes, but it is not recommended to do so
A key-value pair internally uses a colon to separate key and value, separated by commas between different key-value pairs
In particular, an array object is represented by a pair of [] brackets, and the array element can be any type of value


13. Array Class
var arr = ["egg", "Jianguo", "Raibao"];

Array objects are characterized by support for index operations: accessing elements by means of Arr[index]

Array has a length property that represents the number of elements (in fact the length value is the maximum index value +1)

We recommend using the For loop to iterate through the array elements:
for (var i = 0;i<arr.length;i++) {
var element = Arr[i];
}


The array class also provides many ways to manipulate elements:

Push () Adds an element at the end (the number of elements in the array can be changed dynamically)

Unshift () Adding elements at the beginning

Pop () Delete End element

Shift () Delete the beginning element

Note: Arrays also support the normal object's set of operations, but this is not recommended

14. Function functions

1, the function is the first object in JS, it not only has the ordinary object's constructors, attributes, etc., the most important thing is that it can be called

2, usually a function is used to complete a specific action, and can be repeated calls, and those in the object-oriented programming language, similar to the method

3, in view of the function in JS important position, JS provides a variety of syntax to declare, use functions

Actually declaring a function is the object that creates JS's function class.




XV, Function declaration method

Declaration syntax:
Function name (argument list) {
function body
}
Call Syntax: function object ();

Example code:
function sum (n1,n2) {
var sum = n1+n2;
return sum;
}

SUM ();


Function name: composed of letters, numbers, underscores, or $, and cannot start with a number

Parameter list: The parameters that the function expects to receive. Since JS is a weakly typed language, the argument list in the declaration syntax omits Var

function Body: JS code that implements a specific requirement.

Return value type: There is no return value type in the declaration syntax, but the function can use the return statement in the body of the function to return any type of value. If there is no return statement, the default return is undefined

The JS engine in the browser parses and manages functions declared in this way before executing the JS code. So it can be called before this function is declared.

Attention:

JS does not have the concept of function overloading, multiple functions with the same name, regardless of the number of arguments, the name is the same, after the declaration will overwrite the first declared


16. Arguments Array object within function

In the body of the function, the arguments array object can be used directly, and the elements of this array are all arguments actually passed in when this function is called

The number of arguments passed in when the function is actually called can be different from declaring the function, and passing in different types of parameters will cause the result to not match the expected

Since the return value of the JS function and the number of parameters and parameter types are very flexible, we should make sure that the parameters expected to pass in the function when calling

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. Declaration method of function 2, anonymous function

var variable name = function (argument list) {
function body
}

var sum = function (N1,N2) {
var sum = n1+n2;
return sum;
}

sum ();//Call this function


1, this method is also known as anonymous function, JS engine will not be in advance to parse the management of anonymous functions, so anonymous functions can not be called in advance, there is no coverage of the situation

2, in particular, if the variable name is also omitted, you can create a one-time, declared immediately after the call function:
(function (N1,N2) {
var sum = n1+n2;
return sum;
});
The entire function with parentheses as the function name, followed by the passed arguments, is equivalent to calling directly


18, Function declaration Method 3, the original Declaration method

var variable name = new function (argument list, function body);//parameter list and function body all need to be string

var sum = new Function ("N1", "N2", "var sum = N1+n2;return sum");

sum ();//Call this function

This is the most primitive way of declaring, but it is very readable, so you can understand

Since functions are objects of a function class, a function can not only assign a value to a variable,
And can be assigned to another object's properties,
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 function sum to the XXX property of the Obj object
Obj.xxx ();//Call the SUM function

19, the scope of the JS variable

1, the variables directly defined in the <script> tag are global variables, which are valid for all JS code of the entire page.

2,JS pre-defined some global variables, such as name, to be aware of when testing

3,JS engine before executing the code, all the global variable declarations are placed at the top, the assignment statement position is unchanged

4, variables declared in statements such as if, loops, etc. are promoted to global variables as long as the statement executes.

5, a variable can be declared repeatedly and overwritten, using the value of the variable as the last one declared before

6, the variables defined within the function are local variables, local variables are not promoted to global variables, so the outside is inaccessible

7, in two nested functions, the variables defined by the outer function are valid for the inner layer function, and the inverse is invalid.

8, variables defined in two functions that are not nested relationships are not valid for each other

9, pay special attention to the use of variables within nested functions


function A () {
var i = 0;
var B = function () {
Function body Code does not execute when function declaration
var m = i;
Alert (m);
}
i=10;
b ();//When the function executes, the function body code var m = i; Execute, but at this time I is 10;
}

A ();//The result is alert out 10

function A () {
var i = 0;
var B = function () {
alert (B.I);
}
b.i=i;//store I value to a place before the value of I changes
i = 10;
b ();
  
A ();/The result is 0.

20. String class

1, whether the string value of the original type or the object of the string class, has the following properties and methods

Length property: The number of characters in this string

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

Concat (String) concatenation of strings with effect equal to + string connector

IndexOf (String) returns the index position of the first occurrence of the specified string in this string

LastIndexOf (String) returns the index position of the last occurrence of the specified string in this string

Replace (STRING1,STRING2) replaces string1 once with string2

SUBSTRING (number1,number2) take out number1 to number2 in the index range of a substring

Split (string) uses the specified string to slice the string, returning the array of strings after the Shard

Trim () cut off whitespace characters at both ends


21. Date Class

Date class is used to process dates and times based on the number of milliseconds (timestamp) since January 1, 1970 (World Standard Time)

There are several ways to create a Date object:
var now = new Date ();//Current time

var date = new Date (1000);//From January 1, 1970, 1000 milliseconds elapsed

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

The method provided by date:
GetTime () Get? Timestamp on which the date object is based

A series of getter/setter methods are also provided to manipulate the various time components, such as gethours ()

Note: The return value in addition to GetMonth () starts at 0, and the rest starts at 1.


22. Math function of Math

There is a math in 1,js that can be used to perform math tasks, but it doesn't have constructors, so you can't create objects, but it can call functions or properties directly, similar to static classes in other programming languages

2, Common properties:
The MATH.E Euler constant, also the base of the natural logarithm, is approximately equal to 2.718

Natural logarithm of MATH.LN2 2, approximately equal to 0.693

Math.PI Pi, the ratio of the circumference and diameter of a circle, approximately equal to 3.14159

3, Common methods

Math.Abs (x) returns the absolute value of X

Math.ceil (x) returns the value of X rounding up

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

Math.Round (x) returns the rounded integer

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 the pseudo-random number from 0 to 1

Math.sin (x) returns the sine value

23. RegExp class, regular expression

1, regular expressions are a set of independent rules, and almost every programming complaint provides classes that implement this set of rules

2, two ways to create a regular object:
var reg = new RegExp (pattern,flags)
var reg =/pattern/flags
Flags if g, indicates an exact match, if I, ignores case

3,REGEXP provides two common methods:
Test () tests if one end of text matches this regular expression
EXEC () Gets the portion of the text that matches the regular match (the return value is an array or null)

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

Attribute/Index Description Example
[0] matched to the string W
Index matches the character of the original string at the indexed position
Input raw string Hello World


24. JS top-Level object: Window object

1, in JavaScript, whether it is a global variable or a function, the properties of the Window object

The 2,window object represents the entire browser window, not just the JS content, the entire HTML page (including all elements and CSS content) is also under the control of the Window object

3, each time the browser opens a tab, a Window object is created, and the browser window sometimes opens multiple pages, that is, multiple window objects, and each window object almost does not affect

4, in addition to the Window object also provides some other global objects


25. Global Properties of Window

1,location Address Bar Object
HREF attribute
Reload ()
Screenx the distance from the left border of the display browser
Screeny the distance of the right border of the browser from the display
Document page Documents object, representing an HTML page


26, Window's global function

Alert ()//pop-up Prompt box

Confirm ()//Popup Confirmation box

Prompt ()//Popup input Box

Close ()//closes the current page

Open ()//Opens a new tab

SetInterval (), Clearinterval ()

SetTimeout ()//Call function or evaluate expression, cleartimeout () after the specified number of milliseconds


27. JavaScript debugging

1,js code Execution has a feature: from the top down, to explain a sentence to execute a sentence, encountered an error to stop execution

2,JS Code Debugging steps:
Press F12 to open the Debug interface
Select sources
Click the page you want to debug
Refresh page (add breakpoint page as needed)


28, introduction of external JS file

The JS code can be extracted, in this way to introduce:
<script type= "Text/javascript" src= "Test.js" ></script>

The introduction of external JS files in the <script> tag can no longer write JS code, will be ignored, can not be written as a single label form




















Like Peng Web study notes (ix) 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.