Professional JavaScript for WEB developers 3rd Edition---reading notes

Source: Internet
Author: User
Tags array length character classes local time prev

1. Triggering this event when the domcontentloaded Dom tree is built

Load page loading complete trigger

Native JS

function () {    //code ... .. false );d Ocument.addeventlistener (function() {     //code ... false);

Jquery

// domcontentloaded$ (document). Ready (function() {   //code ... }); // load$ (document). Load (function() {  //code ...});

2. Usage in XHTML

Less than (<) again XHTML will be treated as a new label to start parsing, as the label cannot be followed by a space.

Not compatible with XHTML

3. Case-sensitive

The variable name test and test represent two different variables

4. Notes

Single-line Comment

/**/Multi-line comments

5. Strict mode

"Use strict";

6. There are 5 simple data types in Ecmascriptz Undefined, Null, Boolean, number, String

and 1 in complex data type Object (object is actually a set of unordered name value pairs)

7. typeof operator

typeof Null returns an object because a special value of NULL is considered to be an empty objects reference

8. Undefined type

The type has only one value, namely undefined;

When declaring a variable with Var but not initialized, the value of this variable is undefined. VAR message; alert (message);//undefined alert (message = = undefined);//true

If the variable is not declared, an error will be used, such as alert (age); Referenceerror:age is not defined, typeof age//undefined returns undefined using var declaration or no declaration

9.Null type

The type has only one value of NULL

If the defined variable is to be used to hold the object in the future, it is best to initialize it to null.

Undefined derived from null alert (null = = undefined)//true, (= =) equality operator is the purpose of the comparison to convert its operands

Ten. Boolean type

The type has only two literal values of true and False

To convert a value to its corresponding Boolean value, you can call the Transform function Boolean ().

Boolean ("Hello World");//true non-empty string

Boolean ("");//false empty string

These conversion rules the convection control statement (if) automatically performs a corresponding Boolean conversion is very important

Such as

var message = "Hello World";

if (message) {alert}

One. Number Type

11.1 8 binary in front of the number plus 0 if 071 means 57; If the literal value exceeds the range, then the leading 0 is ignored as 079 means 79

Invalid in strict mode

16 binary in the literal 0x a-f can be case-sensitive

11.2 Floating-point number scientific counting method E, the value in front of e multiplied by 10 exponential power var a = 3.123e3//3123

Minimum value Number.min_value

Maximum Value Number.MAX_VALUE

Nan (not a number) b any value divided by 0 will return Nan

Features: 1. NAN/10//nan any operation returns NaN

2. Nan = = Nan//false

11.3 IsNan (param) function Some values that are not values are converted to numeric values, and then return false, such as "10" or True (converted to 1); The value that cannot be converted to a number returns true

11.4 Numeric conversions

There are 3 functions that can convert a non-numeric value to a numeric number (), parseint (), parsefloat

Example

When the parseint function converts a string, it is more about whether it conforms to the numeric pattern, ignoring the space in front of the string until the first non-whitespace character

Example

Attention

Eliminates confusion, provides a second argument (the base binary used when converting)

var num1 = parseint (' AF ', 16);//175

var num2 = parseint (' AF ');//nan

Recommendation: The cardinality is clearly specified under any circumstances

Typical examples of parsefloat

A. String type

Convert to String

Note that null and undefined values do not have this method; The default decimal, you can output other strings in the binary

String () function

Another way to convert to a string (x + "")

Type of Object

3.5 operator

3.5.11-Dollar operator

1. Increment decrement operator

Example

2. Signed integer

3.5.3 Boolean operator

001 Logical Non-

Use two logical non-operators at the same time (!!) Simulates the behavior of a Boolean () transformation function

Example

002 Logic and (&&)

Note: Logic and is a short-circuit operator

003 Logical OR

3.5.4 Multiply sex operator

001 multiplication

002 Division

003 Modulo

3.5.5 additive operator

001 addition

002 Subtraction

A few examples

3.5.6 Relational operators

Character encoding of uppercase letters all less than lowercase characters

Any operand that compares with Nan results in false

var result1 = NaN < 3; False

var result2 = NaN >= 3; False

3.5.7 equality operator

001 equality and inequality (= = and! =)

Comparison of previous conversion operands

Rules when comparing

002 Congruent and non-congruent

Do not convert operands before comparison

var = "result1" = = 55;//true

var result2 = ("55" ===55); False

3.5.8 conditional operator

3.5.9 assignment operator

Compound assignment operator + = and the like

3.5.10 comma operator

The comma operator always returns the last item when used to assign a value

var num = (5, 1, 3, 4, 0);//0

3.6.2 do-while Statements

var i=0;

do{

i+=2;

}while (I<10);

alert (i);

3.6.4 for statement

Because there is no block-level effect in ECMAScript
Domain (this is discussed further in the 4th chapter), so variables defined inside the loop can also be accessed externally.

Even if I is
A variable is defined inside the loop, but it can still be accessed outside the loop.

3.6.5 for-in Statements

This process continues until the object is
All properties are enumerated once. Similar to the For statement, the VAR operator in the control statement is not required. But
To ensure the use of local variables, we recommend this approach in the example above.
The properties of the ECMAScript object are not in order. Therefore, the order of the property names that are output through the for-in loop is unpredictable.

However, if the variable value that represents the object being iterated is null or the Undefined,for-in statement throws an error.
ECMAScript 5 corrects this behavior, and no more errors are thrown in this case, but the loop body is not executed. To ensure maximum

compatibility, it is recommended to detect that the value of the object is not null or undefined before using the for-in loop

3.6.6 Label Statement

3.6.7 Break and Continue statements

Outermost:for () {};

Break:outermost from outermost onwards

Continue:outermost starting from outermost

3.7 Functions

A function in ECMAScript does not have to specify whether to return a value when it is defined actually, any function can be passed at any time.
Return statement followed by the value to be returned to implement the returned value

In addition, the return statement can have no return value. In this case, the function will return undefined after it has stopped executing
Value. This usage is typically used in situations where you need to stop the function execution prematurely without returning a value

3.7.1 Understanding Parameters

This fact illustrates an important feature of the ECMAScript function: named parameters are only convenient, but not required. Other
, in terms of named parameters, other languages may need to create a function signature beforehand, and future calls must be consistent with that signature. But
In ECMAScript, without these rules, the parser does not validate named parameters.

Although this feature is not a perfect overload, but also enough to compensate for the ECMAScript of this shortcoming.

There's something more interesting about arguments's behavior. That is, its value is always kept in sync with the value of the corresponding named parameter.

, this is not to say that reading these two values accesses the same memory space; their memory space is independent, but their values are synchronized.

Also keep in mind that if only one parameter is passed in, the value set for arguments[1] does not reflect
The named parameter. This is because the length of the arguments object is determined by the number of arguments passed in, not by the name defined by the function.
The number of parameters is determined.

4.1 Values for base types and reference types

A primitive type value refers to a simple data segment, whereas a reference type value refers to an object that may consist of multiple values.

4.1.1 Properties of the dynamic

var person = new Object ();

Person.name = "Zhangsan";

4.1.2 Copy variable values

4.1.3 Passing parameters

4.1.4 Detection Type

typeof detection Basic Type

Know what type of object a value is instanceof

var result = Variable instanceof constructor

If the variable is an instance of a given reference type, then Instanceof returns True

If you use instanceof to detect a value of a base type, the operator always returns false because the base type is not an object

4.2 No block-level scope

Any code that is after the declaration of a local variable color that cannot access the global color variable if you do not use Window.color

4.3.2 Reference count

Eliminate circular references

Myobject.element = null;

Element.someobject = null;

To solve these problems, IE9 has converted both BOM and Dom objects into real JavaScript objects. In this way, it avoids the
The problems caused by the coexistence of two garbage collection algorithms also eliminate the common memory leak phenomenon.

5.1 Object Objects

There are two ways to create object objects:

001 new operator

var person = new Object ();

Person.name = "Zhangsan";

002 Object Literals

var person = {

Name: "Zhangsan",

Age:19

};

You can use square brackets to access the properties of an object

person["First Name"]

5.2 Array Type

There are two basic ways to create an array

001 Array Constructor

var color = new Array ();

002 Using array literals

var color = ["Red", "Blue", "green"];

The number of items in the array is saved in the Length property (0+) By setting this property, you can remove an item from the end of the array or add a new item to the array

var colors = ["Red", "Blue", "green"];

Colors.length = 2;

Alert (colors[2]);//undefined

Colors.length = 4;

Alert (colors[3]);//undefined

This feature makes it easy to add new items

Colors[colors.length] = "Gray";

Colors[colors.length] = "yellow";

5.2.1 Detecting arrays

5.2.2 Conversion method

All objects have tolocalestring (), toString (), and valueOf () methods

var colors = ["Red", "Blue", "green"]; Create an array with 3 strings
Alert (colors.tostring ()); Red,blue,green
Alert (colors.valueof ()); Red,blue,green
alert (colors); Red,blue,green

If you use the Join () method, you can use a different delimiter to create the string

Colors.join ("&");//Red&blue&green

5.2.3 Stack method

The push () method can receive any number of arguments, add them to the end of the array one by one, and return the length of the modified array. and
The Pop () method removes the last item from the end of the array, reduces the length value of the array, and then returns the item that was removed.

var colors = new Array ();

var count = Colors.push ("Green", "blue");

alert (count);//2

var item = Colors.pop ();

alert (item);//blue

5.2.4 Queue method

So to simulate a queue requires only one way to get items from the front of the array. The array method for doing this is shift (), which can move
The first item in the divisor group and returns the item, minus 1 of the array length. Using the shift () and push () methods together, you can
Use arrays in the same way as queues.

var item = Colors.shift ();

alert (item);//green

Unshift () is the opposite of the use of Shift ():
It can add any item to the front of the array and return the length of the new array. Therefore, using both the Unshift () and the Pop () methods, you can
Simulate a queue in the opposite direction, that is, add items to the front of the array, remove items from the end of the array

5.2.5 reordering

There are two reordering methods in the array

Reverse () Reverses the order of array items

Sort () even if each item in the array is a numeric value, the sort () method compares the string (the ToString () method that calls each item and then compares the string)

var values = [0, 1, 5, 10, 15];
Values.sort ();
alert (values); 0,1,10,15,5

The

Sort () method can receive a comparison function as a parameter so that we specify which value is in front of which value. The
comparison function receives two parameters, returns a negative number if the first argument should precede the second, and returns 0 if two arguments are equal
, or returns a positive number if the first argument should be in the second one

function Compare (value1, value2) {//ascending if (value1 < value2) {return -1else< /c6>if (value1 > value2) {return 1else  {return 0;}} var values = [0, 1, 5, ten,//0,1,5,10,15

5.2.6 Method of operation

001 concat () method

002 Slice () method

003 Splice () method

The splice () method always returns an array that contains the items removed from the original array (if no
Item, an empty array is returned)

5.2.7 Location method

IndexOf ()

LastIndexOf ()

var numbers = [1,2,3,4,5,4,3,2,1];
Alert (Numbers.indexof (bis));
Alert (Numbers.lastindexof (4, 4));

5.2.8 Iterative method

varnumbers = [1,2,3,4,5,4,3,2,1];varEveryresult = Numbers.every (function(item, index, array) {return(Item > 2);}); alert (Everyresult); //falsevarSomeresult = Numbers.some (function(item, index, array) {return(Item > 2);}); alert (Someresult); //True

var filterresult = numbers.filter (function (item, index, array) {
Return (item > 2);
});
alert (Filterresult); [3,4,5,4,3]

var mapresult = Numbers.map (function (item, index, array) {
return item * 2;
});

alert (Mapresult); [2,4,6,8,10,8,6,4,2]

The Last method is foreach (), which simply runs the incoming function for each item in the array. This method has no return value,
is essentially the same as using a for loop to iterate over an algebraic group. Take a look at an example.
var numbers = [1,2,3,4,5,4,3,2,1];
Numbers.foreach (function (item, index, array) {
Perform certain actions
});

5.2.9 Merge method

Reduce () and reduceright (). Both of these methods iterate over all the items of an algebraic group and then build a value that is ultimately returned.

where the reduce () method starts with the first item in the array and traverses through to the end.

and Reduceright () begins with the last item in the array and traverses forward to the first item

The functions for reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object. This
Any value returned by a function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the
One parameter is the first item of the array, the second is the second item of the array

var values = [1,2,3,4,5]; var sum = values.reduce (function(prev, cur, index, array) {return prev +  //  the

Reduceright () acts similarly, except in the opposite direction.

5.3 Date Type

var now = new Date (); The newly created object automatically obtains the current date and time without passing arguments

The 001 Date.parse () method receives a string parameter that represents a date, and then attempts to return the number of milliseconds of the corresponding date based on the string.

If you pass a string that represents a date directly to the date constructor, the Date.parse () is also called in the background

var somedate = new Date (Date.parse ("May 25, 2004"), equivalent to

var somedate = new Date ("May 25, 2004");

002 DATE.UTC () Date and time are created based on the local time zone rather than GMT

GMT time May 5, 2005 5:55:55
var allfives = new Date (DATE.UTC (2005, 4, 5, 17, 55, 55));

local time May 5, 2005 5:55:55
var allfives = new Date (2005, 4, 5, 17, 55, 55);

003 Data.now ()

Get Start time
var start = Date.now ();

Using the + operator to convert the data object to a string can also achieve the same purpose.

Get Start time
var start = +new Date ();

Methods of 5.3.1 Inheritance

The Date type also overrides the toLocaleString (), toString (), and valueof () methods;

5.3.3 Date/Time component method p120

5.4 RegExp Type

Create regular expression var expression =/pattern/flags;

The pattern section can be any simple or complex regular expression that can contain character classes, qualifiers, groupings, forward lookups, and reverse references

The matching pattern for regular expressions supports the following 3 flags.
? G: Represents the global mode, that is, the pattern will be applied to all strings, not immediately when the first match is found
Stop
? I: Indicates case insensitive (case-insensitive) mode, which ignores the case of patterns and strings when determining matches;
? M: represents multi-line (multiline) mode, that is, when the end of a line of text is reached, it will continue to find out whether the next row exists in the
Match the item.

Therefore, a regular expression is a combination of a pattern with the above 3 flags. Different combinations produce different results

001 regular expressions defined in literal form

/* * Match all ". At", case insensitive */ var pattern4 =/\.at/gi;

002 RegExp constructor to create a regular expression

/* * Same as PATTERN1, but created using the constructor function */ var New RegExp ("[Bc]at", "I");

ECMAScript 5 explicitly stipulates that the use of regular expression literals must be the same as calling the RegExp constructor directly, each time creating an
Create a new RegExp instance.

5.5 Function type

The function is actually an object

Each function is actually an instance of the type function

p128

Professional JavaScript for WEB developers 3rd Edition---reading notes

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.