JavaScript Advanced Programming (Third Edition) Learning Notes 1~5 Chapter _javascript Skills

Source: Internet
Author: User
Tags array length bitwise eval first string garbage collection month name wrapper hasownproperty

2nd chapter, using JavaScript in HTML

HTML introduces external JS script

<script type= "Text/javascript" src= "Test.js" > Two </script> should not be placed between scripts because it will not be executed </script>


<script> tag has a defer property that can delay script execution, but does not guarantee that it will be executed in a script order

Recommendation: put the script into the <body> tag after all the content, but not in the

The contents of the <noscript></noscript> label will output when the browser does not support script or the script is disabled, and script-enabled browsers will not see the

Content

The 3rd chapter, the basic concept

Identifier

The first character must be a letter, an underscore (_), or a dollar sign ($), which is effectively named as a letter, number, underscore, and dollar sign.

Using the Hump nomenclature: The first letter is lowercase, the first letter of each word is capitalized

Single-line Comment:

This is a single-line comment

Multi-line Comment:

* * This is
MultiRow
Comments
*/

typeof operator

typeof– determine the data type of a given variable

Return:

"Undefined" – Undefined data type

"Boolean" – Boolean value

' String '-string

"Number" – Numeric value

"Object" – Object or null

"Function" – functions

Note: The function is an object in JS, not a data type, so it is necessary to use TypeOf to differentiate functions and objects.

typeof sometimes returns confusing but technically correct values, such as null and objects, both of which return "object"

Null is equal to undefined, NULL = = undefined returns true

For arithmetic calculations, all octal and hexadecimal are converted to decimal

Infinity infinity, with positive and negative infinity, you can use Isfinite () to determine whether infinity

Number.max_value,number.min_value holds the maximum and minimum values of the numeric type, respectively.

Number.negative_infinity and number.positive_infinity were kept in negative and positive infinity respectively.

NaN Non-numeric, you can use isNaN to determine whether a variable is not a numeric value

numeric conversions

Cast number (), but the result is not reasonable, it is recommended to use the parseint () function and bring it into the cardinality that needs to be converted

Cases:

parseint ("10", 2); Parsing
parseint ("10", 8) in binary form;//octal

Not bringing in the cardinality means letting parseint decide how to parse the string, which can cause errors at some point

Parsefloat () is essentially the same as parseint (), resolves strings to floating-point numbers, always ignores leading zeros, resolves only decimal values, and hexadecimal is parsed into 0, so

He doesn't have a second argument.

String type

The string type variable is immutable, that is, the string variable is a constant, you can use single quotes ('), or you can use double quotes (") to define a string variable, but you must match it, and if you need to mix it, we recommend that you add the escape character (\)

Using the ToString () function to convert a value to a string, the value can be converted using a cardinal value

Cases:

var num = ten;
Num.tostring ("2"); "1010"
num.tostring ("8");//"12"

You can also use String () to cast

Object type

Constructor: Constructors

hasOwnProperty (PropertyName): Checks whether a given property exists in the current object

isPrototypeOf (object): Checks whether the incoming object is a prototype of an incoming object

propertyIsEnumerable (PropertyName): Checks whether a given property can be enumerated using a for-in statement, as with hasOwnProperty, a given property name must be specified as a string

Tolocalstring (): Returns the string representation of an object that corresponds to the locale of the execution environment

ToString (): Returns the string representation of an object

valueof (): Returns a string, numeric, or Boolean representation of an object. Usually returns the same as ToString

Operator

Bitwise NON: ~, bitwise AND: N, by-position or: |, bitwise XOR: ^, left: <<, signed right:>> (filled with symbol bit), unsigned right:>>> (filled with 0), logical non:!, logical AND: && Logic or: | |

Relational operator: <,>,<=,>=

Equality and Inequality: ==,!=, first convert and then compare

Congruent and not congruent: ===,!==, compare only, do not convert, type is different

Conditional operator:? : The triple-Mesh operator

Comma operator: (,), returns the value of the last expression: var num = (3,5,6,2), num = 2

Statement

If{},do{}while ();, while () {},for (;;) {}

For-in statement:

An accurate iteration statement that can be used to enumerate the properties of an object

For (property in expression) statement

Cases:

for (var propname in window) {
document.write (propname);

Note: for-in error occurs when the object's variable value is null or undefined, although ECMAScript5 changes the error, but in order to maximize compatibility, before using the for-in loop, First detects that the value of the object is not null or undefined

Label Statements: Label statements

Start:for (var I = 0;i<count;i++) {
statement

This start tag can be used in subsequent break and continue statements, which are typically used with circular statements

With statement:

To set the scope of the code to a specific object

With (expression) statement;

The WITH statement is not allowed in strict mode, otherwise it will be treated as a syntax error

A large number of use with statements can cause performance degradation and code debugging difficulties, and it is recommended that the development of large applications do not use the WITH statement

Switch statement

switch (expression) {case
selection:statement;
break;
..... default:statement;
break;

Function

Strict mode for function restrictions:

Functions cannot be named eval and arguments

Parameter cannot be named eval and arguments

Cannot have two named parameters with the same name

Understanding function Parameters

The function in JS does not mind how many function arguments are passed in, even if it is different from the defined case, because the function is always receiving an array-like argument, and the function does not care about the parameters contained in the array. This parameter array can be accessed through the arguments object in the function body.

Arguments is just like an array, because you can use square brackets to access its elements, using length to determine the number of parameters that are passed in. The order of the parameters in the arguments is in accordance with the sequence of parameters that are passed in, and it is changed synchronously.

Note: A named parameter that does not have a value passed is assigned a value of undefined.

Strict mode restricts arguments objects: assigning values to arguments in a function will become invalid, overriding arguments values will cause syntax errors

Using arguments to judge the type and number of parameters, you can mimic the overload

4th chapter, variables, scope and memory issues

Note:the parameters of all functions in JS are passed by value

Detection type: instanceof

The instanceof operator can only manipulate reference types, that is, objects, and tests on the base data type always return True because the base data type is not an object

result = Variable instanceof constructor

Returns TRUE if the variable is the given reference type

Cases:

Person instanceof Object; is person type object?
Color instanceof Array; is color the array type?

No block-level scope

if (true) {
var j = ' Blue ';
}
Alert (j);

If an error occurs in C + +, and JS does not, the variable defined in the block will be added to the scope outside the current curly braces.

Garbage collection

Mark Clear

Reference count

5th chapter, Reference type

Object type

Two ways to create an instance:

First, use the new operator followed by the object constructor

var obj = new Object ();
Obj.name = "name";

Second, the object literal is used (when you define an object by its literal literals, it does not actually call the object constructor)

var obj = {
name: ' Name ';
Age:23
}

You can access the properties of an object by using dot notation and square brackets notation

Point notation: Square bracket notation: (must represent the property name to be accessed as a string)

Obj.name obj["Name"]

Note: When the property name contains a character that causes a syntax error, or if the property name uses a keyword or reserved word, you can use the square brackets notation, and you can access the property through the variable

Recommendation: Unless you must use a variable to access the property, it is a good idea to use dot notation

Array type

How to create:

First, use the array constructor

var arr = new Array (); Create an empty array
var arr = new Array (20);//Create an array of 20 items
var arr = new Array ("One", "two", "three");//Create a containing one,two, An array of three three 
can also omit the new operator

Second, using the literal representation of the array

var color = ["Red", "Blue"]; Create an array that contains two items

Note: Array constructors are not invoked when arrays are created using the literal amount of an array

Arr.length, the number of items in the array will be returned, and the size of the array is about to be returned

Assigning values to Arr.length will dynamically alter the size of the table array, assigning a value greater than the original array size expands the array, the new item obtains the undefined value, is less than the original array size, will retain the preceding value, many values will be removed

Array Detection:

For a single global scope, instanceof can easily detect whether a variable is an array, but for pages of multiple frames, there are several different versions of the array constructor, and instanceof will not be able to meet the requirements. This introduces the Array.isarray (value) method, which can ultimately determine whether a value is an array, regardless of which frame is constructed. The supported browsers are: Ie9+,firefox4+,safari5+,opera10.5+,chrome.

Conversion method:

Call the ToString () method of the array, which returns a comma-delimited string of strings of each value in the array, and the valueof () method returns an array with the same result as ToString ()

toLocaleString () returns usually the same result as ToString () and valueof (), but not always, using the toLocaleString () method, the toLocaleString () method of each item in the array is invoked , rather than the ToString () method.

Join method

The Join method accepts an argument, a string that is a delimiter

Cases:

var arr = ["One", "two"];

Returns a comma-delimited string If no arguments are passed to a join

Note: If the value of an item in the array is null or undefined, then call join,tolocalestring (), toString (), and valueof () The result returned by an empty string representation

Stack method of arrays

var arr = new Array ();

Arr.push (), add data at the end of the array, pass in multiple parameters, and return the modified array length

Arr.pop (), removes the last data from the end of the array, reduces the length value of the array, and returns the value of the item

The queue method of an array

var arr = new Array ();

Arr.shift (), moves the first item of the divisor group, reduces the length of the array, and returns the value of the item

Arr.unshift (), add any items to the front of the array, and return the modified array length

With shift and push, you can simulate queue operations

Using unshift and pop combinations, you can simulate queues in the opposite direction

Reorder Method:

var arr = new Array ();

Arr.reverse (), flip the items of an array, that is, the order of the tail

Arr.sort (), by default ascending order, note: The order is an ascending arrangement after the array value is converted to a string, usually not the desired sort

The Sort method can accept a comparison function as an argument, implement the desired sort method, return a negative number in ascending order, and return an integer in descending order, note: You can adapt to most sorts

Action method:

var arr = new Array ();

Arr.concat (), making an array connection, and returning the concatenated array, passing in multiple parameters

Arr.slice () can be returned by creating a new array based on one or more values in the current array. Accepts one or two arguments, returning all items between the start and end positions of the original array, not the ending position, and only one parameter that returns all items from the specified position to the end of the argument.

Note: If the argument is a negative number, the length of the array is added to the result of the negative number to determine the position. Returns NULL if End position is less than start position

Splice () Method:

Delete: Specify two parameters, the starting position to delete and the number of items to delete, for example: Splice (0,2);

Insert: Specify three parameters, starting position, number of items to delete (0), items to insert, inserted items can be multiple items

Example: Splice (2,0, "Red", "green"); Insert Red,green from position 2

Substitution: Same as INSERT, second parameter has change, starting position, number of items to be deleted, items to insert, number of items inserted can be multiple items

Location Method:

IndexOf (), LastIndexOf (), both receive two parameters, the item to find and the lookup Start position index indexOf start looking from the array header, LastIndexOf start looking from the end of the array. If not found, return-1.

Note: The comparison used in the lookup is the congruent operator, just like using "= ="

Iteration Method:

ECMASCRIPT5 defines 5 iterative methods, all of which receive two parameters: the function that runs on each item, and the scope object that runs the function-the value that affects this. The function receives three parameters: the value of the array item, the position of the item in the array, and the arrays of objects themselves

var arr = new Array ();

Every (), returns True if each entry in the array runs the given function, and each entry returns true

Filter (), which runs the given function for each item of the array, and returns an item consisting of the items that the execution function returns true

Cases:

var num = [1,2,3,4,5,4,3,2,1];
var filter = Num.filter (function (item,index,array) {return
item > 2;

ForEach (), each item in the array runs the given function, has no return value, and is essentially consistent with the For loop iteration Group

Map (), which runs the given function for each item in the array, and returns the result of each function call

Some (), each item in the array runs the given function, and returns true whenever the function result of either item is True

Note: All of the above functions do not modify the array

Cases:

var num = [1,2,3,4,5,4,3,2,1];
var mapresult = Num.map (function (Item,index,array () {return
item * 2;
});

Merge method:

Reduce () and reduceright ()

Two functions iterate over all the items of the group, and then build a final returned value where reduce starts with the first item of the array, reduceright from the last item in the array

Both methods receive 2 parameters: a function called on each item and (optionally) the initial value that is the base of the merge. The passed function needs to receive 4 parameters: the previous value, the current value, the index of the item, and the array object. The return value of this function is passed to the next item as the first argument, and the first iteration takes place on the second item of the array, so the first argument is the first item of the array, and the second is the second item of the array.

Cases:

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

The first time the callback function is executed, prev = 1,cur = 2, the second time, prev = 3 (the first function returns the result 1+2), cur = 3 (the current array entry). This process accesses each item in the array.

Reduceright except the direction is different, the others are the same.

Date type

The date type uses the number of milliseconds since UTC1970.1.1 midnight 0 o'clock to save dates, which can be accurate to 100 000 000 (100 million) years before or after 1970.1.1.

By using the date constructor without arguments, the new object obtains the current date and time, and to create a specific datetime, you must pass in the number of milliseconds representing that date, ECMAScript provides two methods Date.parse and DATE.UTC methods to simplify the operation.

The Date.parse method receives a string parameter that represents a date. This method varies by implementation and usually varies by region. Browsers in the U.S. region support the following formats:

Month/day/year, such as 6/13/2004

English month name day, year, such as January 12,2004

English name days of the week English month: minutes: Second time zone, such as Tue May 00:00:00 GMT-0700

ISO 8601 extended format yyyy-mm-ddthh:mm:ss.sssz, such as 2004-05-25t00:00:00, supports this format only for JS5 implementations

DATE.UTC also returns the number of milliseconds for the date, the parameters are: year, 0 months (January is 0), Day of the Month (1-31), Hours (0-23), minutes, seconds, and milliseconds, where only the first two parameters are required.

Cases:

var somedate = new Date (DATE.UTC (2000,0)); January 1, 2000 0:0 0 seconds

The date constructor mimics the Date.parse and DATE.UTC functions.

The Date.now method returns the number of date and time milliseconds that the function was called. In unsupported browsers, you can use the + operator to get the Date object timestamp

var start = +new Date ();
var stop = +new Date ();

Day Formatting method

todatestring-Displays the day, month, days, and years in an implementation-specific format

totimestring-displays time, minutes, seconds, and time zones in an implementation-specific format

tolocaledatestring-Displays the week, month, day, and year in a locale-specific format

tolocaletimestring-displays time, minutes, and seconds in an implementation-specific format

toutcstring-complete UTC time in the implementation-specific format

As with toLocaleString and ToString, none of the above methods can be used to display consistent date information in the user interface.

RegExp type, regular

Syntax: Similar to Perl syntax

var expression =/pattern/flags;
The pattern section can be a simple or complex regular expression that can use one or more identifiers and support the following 3 identifiers

G: Global mode, which will be applied to all strings instead of stopping after the first string is matched.

I: Indicates case-insensitive,

M: multiple-line mode, when the end of a line of text is reached, continues to find the next line

Note: All meta characters in the pattern need to be escaped

Metacharacters: ([{^ $ |}? * +.])

The above method is to create a regular expression in literal mode

Constructing regular expressions using RegExp

var partten = new RegExp ("Bat", "I");

Note: Using the RegExp constructor, all metacharacters must be escaped twice

Example:/\[bc\]at/===> "\\[bc\\]at"

RegExp Instance Properties

Global: Boolean value that indicates whether the G flag is set

IgnoreCase: Boolean value indicating whether I flag is set

Lastindex: An integer that represents the character position of the next occurrence of the search, starting at 0

Multiline: Boolean value that indicates whether the M flag is set

Source: The string representation of the regular expression, in literal form, rather than in the string pattern in the incoming constructor

The main method for RegExp objects is exec (), exec () receives a parameter, the string to which the pattern is to be applied, and returns a match (even if the G-Flag is set), there is no difference between the G-flag setting, the same result is always returned, and the next match is set.
The test method, which receives a string, returns only whether it matches, and does not return a result

function type

function is an object, the function name is a pointer

To define a method:

function declaration form function
sum (num1,num2) {return
num1 + num2;
}
The form of a function expression
var sum = function (num1,num2) {return
num2 + num2;
}
var sum = new Function ("num2", "num2", "return NUM1 + num2"); Not recommended, performance slag, but can better understand the function is the object of thought. 
function Add (num) {return
num +;
}
function Add (num1,num2) {return
num +
}
This is actually like the following code
function add (num) {return
num +;
}
add = function (num) {return
num +
}

So the function has no overloads.

Function Internal Properties

There are two special objects inside the function, arguments and this

Arguments has a property callee that points to the function that owns the arguments.

When defining recursive functions, it is best to use Arguments.callee () instead of function names, reduce coupling, and reduce the occurrence of problems

Cases:

function factorial (num) {
if (num<1) return
1;
else return
num * factorial (num–1);
}
function factorial (num) {
if (num<1) return
1;
else return
num * Arguments.callee (num–1);
}

This object

The This object of the function refers to the environment object to which the function was executed

The ECMASCRIPT5 specification defines the properties of another function object: caller, which holds a reference to the function that calls the current function.

The function contains two attributes: Length (the number of functions you want to receive) and Prototype,prototype cannot be enumerated, so for-in cannot find him. Prototype is the true location of all reference types that hold all instance methods

Contains two methods that are not inherited: Apply and call

The Apply method receives two parameters: one is the scope in which the function is run, that is, the this object, one is a parameter array, can be an array instance, or it can be a arguments object

Call is basically the same as apply, except that, using the call function, parameters must be enumerated individually

Passing parameters are not the real place to apply and call, the real powerful thing is the ability to expand the scope of a function

Cases:

Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
alert (this.color);
}
Saycolor (); Red
Saycolor.call (this);//red
saycolor.call (window);//red

You do not need to place the Saycolor function in the O object, so that the O object can use the Saycolor function

ECMAScript5 also defines another method: Bind, which creates a function instance whose this value is bound to the value passed to the BIND function

Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
alert (this.color);
}
var objsaycolor = Saycolor.bind (o);

toLocaleString and ToString always return function code, but because of browser differences, there is no way to implement any important functionality based on the return result, valueof also returns only the function code

Basic Packing Type

Boolean, number, String

Calling typeof on an instance of the base wrapper type returns object, and all instances of the base wrapper type return True.

The object constructor, like the factory method, returns an instance of the base wrapper type of the response based on the type of the value passed in

Cases:

var obj = new Object ("some text");

Invoking the basic wrapper type with new is not the same as using the transition function with the same name directly. Cases:

var value = "a";
var num = number (value); Transition function
alert (typeof num);//"number"
var obj = new number (value);//constructor

Number Type

Additional methods provided

ToFixed (); receives a parameter indicating that the current value is to be expressed in several decimal places, and that the current decimal position is rounded, and this method can represent a value with 0 to 20 decimal places, which is only the standard implementation scope

Toexponential (); receives a parameter, returns an exponential representation, and the parameter specifies the number of decimal places in the returned result

Toprecision (); receives a parameter that represents the number of digits for all digits, excluding the exponent part

String type

var str = "Hello world";
Str.charat (1); "E", returns the character
str.charcodeat (1);//"101", returns the character encoding
str.concat ();//connection string, can receive any string 
slice (), substring (), SUBSTR (), receives one or two parameters, receives the first parameter all represents the starting position, slice (), substring () receives the second parameter to indicate the termination position, substr () the second parameter indicates the number of characters returned, if not to the second argument, Returns the character from the start position to the end of the string

Bring negative numbers differently: Slice adds all the negative numbers that are brought in to the string length, substr the first argument with the string length, and the second argument to 0,substring () converts all negative values to 0

The Indexof,lastindexof method returns the position of the substring, indexOf looking from the bottom, lastindexof looking from the end, not finding return 1, and two methods can receive the second optional parameter, indicating where the character starts the search

Trim (), returns the result of all blanks in the source string deletion prefix

Tolowercase,tolocalelowercase,touppercase,tolocaleuppercase, the locale approach is for specific areas of the implementation. Typically, there is no difference, but a few languages apply special rules for Unicode case conversions, which must be done with specific locale

Match (), search () both methods receive a parameter, a string, or a regular expression specified by the RegExp object

Replace () method, receives two parameters, the first argument can be a RegExp object or string (not converted to a regular expression), the second argument can be a string or function, and to replace all strings, you must use regular expressions and add the global (g) flag

Split (), which receives a parameter as a delimiter for the string, returns an array separated by delimiters, and receives the second optional argument as the size of the array to return the result

Localecompare (), comparing two strings, about whether case sensitive, depending on the region

1, the source string should be ranked before the parameter string, return a negative number (depending on the case, usually-1)

2, the source string is the same as the parameter string, returns 0

3. The source string, after the parameter string, returns an integer (depending on the case, usually 1)

fromCharCode (), receives one or more character encodings, converts to strings, and performs the opposite operation with charCodeAt ()

URI (Universal Resource Identifier)

Methods: Encodeuri,encodeuricomponent,decodeuri,decodeuricomponent, encoding and decoding, decoding methods can only identify their corresponding coding methods

Eval (), converts the string parameter that is brought into the executable statement and inserts it into the current position

Any variables and functions created by Eval are not promoted, and the variables and functions created by eval cannot be accessed externally in strict mode

Note: Try not to use eval method, only personal opinion

Math Object

Min (), Max (), ceil () rounded up, floor () rounded down, round () standard rounding, rounded, random () returns a random number greater than or equal to 0 less than 1

The above is a small set to introduce the JavaScript Advanced Programming (Third Edition) learning Notes 1~5 Chapter, I hope to help you!

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.