JavaScript Advanced Programming (3rd Edition) Chapter Fifth reading notes

Source: Internet
Author: User
Tags access properties character classes instance method time zones rounds alphanumeric characters

Fifth Chapter reference types

    1. There are two ways to create an object instance, the first of which is to use the new operator followed by the object constructor, for example:

var person = new Object ();

Person.name = "Nicholas";

person.age=29;

The second is the use of object literal notation. Such as:

var person = {

Name: "Nicholas",

Age:29

};

Adding a comma after the last property causes an error in IE7 and earlier versions and opera.

    1. two methods for accessing object properties, one is square bracket syntax, such as person["name", and the other is point notation, such as Person.name. The main advantage of square brackets syntax is that you can access properties by using variables. If the property name contains a character that causes a syntax error (the property name contains non-alphanumeric characters), or if the property name uses a keyword or reserved word, you can also use square brackets notation. In general, the point notation is more recommended.
    2. differs from other languages in that each item of the ECMAScript array can hold any type of data, and the size of the ECMAScript array can be dynamically adjusted, that is, it can grow automatically as the data is added to accommodate the new data.
    3. There are two basic ways to create an array: One is to use the array constructor, such as var colors = new Array (), and the second method is to use the array literal notation. such as var colors = ["Red", "Blue", "green"]; do not end with commas to avoid confusion. if var values = [1, 2,], an array containing 2 or 3 items is created. The length property of the
    4. array is not read-only and can be customized to remove an item from the end of the array or to add a new item to the array.
    5. for a Web page, or a global scope, you can get satisfactory results using the instanceof operator. The problem with the instanceof operator, however, is that it assumes that there is only one global execution environment. Therefore, ECMASCRIPT5 has added the Array.isarray () method. The purpose of this method is to ultimately determine whether a value is an array, regardless of which global execution environment it was created in. Browsers that support the Array.isarray () method are ie9+, firefox4+, safari5+, opera10.5+, and Chrome.
    6. All array objects have the tolocalestring (), toString (), and valueof () methods. The ToString () method in which the array is called returns a comma-delimited string that is stitched together as a string of each value in the array. The Valueo () returns an array. Note: alert () receives the string parameter, so it calls the ToString () method in the background. The
    7. join () method can use a different delimiter to construct the string. The Join () method receives only one parameter, which is a string used as a delimiter, and then returns a string containing all the array items.

such as var colors = ["Yellow", "red", "green"];

Alert (Colors.join ("|")); Yellow|red|green

If you do not pass any value to the join () method or pass it to undefined, use a comma as the delimiter. IE7 and earlier versions would incorrectly use the string "undefined" as the delimiter.

    1. The data structure of the stack method (last in, first out) of the array. 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. 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.
    2. Array of queue methods (FIFO). The queue adds items at the end of the list, removing items from the front end of the list. Still use push () to add an item to the end of the array, use SHIFT () to get the first item from the front of the array and return the item, minus 1 of the array length. The Unshift () method, in contrast to the use of shift (), can add any item to the front of the array and return the length of the new array.
    3. The two reordering methods of the array: the reverse () method flips the order in which the array is to be sorted, sort () arranges the array items ascending, and the sort () method invokes the ToString () transformation method of each array item, and then compares the resulting string to determine how to sort. Therefore, the sort () method can receive a comparison function as an argument to specify which value is in front of which value.
    4. The Concat () method of the array can create a copy of the current array based on all the new arrays created in the current array, and then add the received parameters to the end of the copy.

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

var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]);

Colors//["Red", "green", "blue"

Colors2//["Red", "green", "blue", "yellow", "black", "Brown"]

    1. The slice () method of the array that creates a new array based on one or more items in the current array. Receives one to two parameters, that is, the item that returns the start and end of the item, but does not return the end position.

var colors3=colors2.slice (1); ["Green", "blue", "yellow", "black", "Brown"]

var colors4 = Colors2.slice (1,4); ["Green", "blue", "yellow"]

The slice () method has a secondary parameter in it, then the array length is used to determine the corresponding position.

var colors5 = Colors2.slice ( -2,-1); ["Black"]

    1. The splice () method of an array is the most powerful array method, and the main purpose is to insert items into the middle of the array.

Delete: Can or delete any number of items, just specify 2 parameters: The position of the first item to be deleted, and the number of items to be deleted;

Insert: You can insert any number of items to a specified location, specifying 3 parameters: Start position, 0 (number of items to delete), number of items to insert.

Replace: You can insert any number of items at the specified location and delete any number of items at the same time, specifying 3 parameters: The starting position, the number of items to delete, and any number of items to insert.

The Splice () method always returns an array that contains the items that were deleted from the original array (fan hu an empty array if no items were deleted).

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

var removed = Colors.splice (0,2);

Colors//["Blue"]

Removed//["Red", "green"]

removed = Colors.splice (0,0, "Yellow", "orange"); //[]

Colors//["Yellow", "orange", "Blue"]

removed = Colors.splice (1,3, "red", "pink"); ["Orange", "Blue", "yellow"]

Colors//["Yellow", "red", "pink", "orange"]

var colors = ["Yellow", "orange", "Blue"];

removed = Colors.splice ("Red", "pink"); ["Orange", "Blue"]

Colors//["Yellow", "red", "pink"]

    1. Array Location Lookup methods: IndexOf () and LastIndexOf (). Both methods receive two parameters: the subparagraphs (optional) to find indicates the index at which to find the starting point. Success returns the position of the first occurrence of the found item in the array, otherwise returns-1. The congruent operator is used during the comparison.

var numbers = [1,2,3,4,5,4,3,2,1];

Numbers.indexof (4); 3

Numbers.indexof ("4"); -1

Numbers.lastindexof ("4"); -1

Numbers.lastindexof (4); 5

Numbers.indexof (bis); Look backwards from the starting position

Numbers.lastindexof (//3) Looking forward from the starting position

Numbers.lastindexof (4,5)//5 looking forward from the starting position

var person ={name: "Nicholas"};

var people=[{name: "Nicholas"}];

var morepeople = [person];

People.indexof (person); -1

Morepeople.indexof (person); 0

    1. ECMAScript 5 defines 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this. The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the group object itself.

Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item;

Filter (): Each item in an array runs the given function, and returns a list of the items that the function returns true;

ForEach (): Runs the given function for each item in the array, with no return value;

Map (): Each item in the array runs the given function, returning an array of the results of each function call;

Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

None of the above methods will modify the contained values in the array.

    1. Array Merge methods: 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. The reduce () method starts with the first item of the array, traverses through to the last, and Reduceright () iterates through the first item, starting with the last item in the array.
    2. Date type, creation method: var now = new Date ();

The 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 the string cannot represent a date, Nan is returned.

DATE.UTC () returns the number of milliseconds of the date, but with Date.parse () uses different information at build time.

ECMAScript 5 adds the Date.now () method, which returns the number of milliseconds that represent the date and time when this method was called.

    1. The toLocaleString () and ToString () methods of the date type, which return a different date format, are represented by the ValueOf () method, which returns the milliseconds of the date.
    2. Date formatting methods:

toDateString ()-Displays the day of the week, months, days, and years in an implementation-specific format;

toTimeString ()-Displays hours, minutes, seconds, and time zones in an implementation-specific format;

toLocaleDateString ()-Displays the day of the week, months, days, and years in a region-specific format;

toLocaleTimeString ()-Displays the time, minutes, and seconds in an implementation-specific format;

toUTCString ()--full UTC date In a format that is specific to the implementation.

There is no method that can be used to display consistent date information in the user interface.

    1. Date/Time component method, see book 102 page.
    2. RegExp type, literal form syntax is: var expression =/pattern/flag; The pattern section can be any simple or complex regular expression that can contain character classes, qualifiers, groupings, forward lookups, and reverse references. Each regular expression can have one or more flags (flags) that indicate the behavior of the regular expression.

G: Represents the global mode, which means that the pattern will be applied to all strings, rather than stopping immediately when the first occurrence is found;

I: Indicates case-insensitive mode, that is, the case of the pattern and the string are ignored when the match is determined;

M: represents multiline mode, that is, when the end of a line of text has not yet continued to find the next line, whether it exists in the pattern matching items. Remember: Don't look forward.

All metacharacters used in the pattern must be escaped, and the metacharacters in the regular expression include:

( [ { \ ^ $ | } ? * + . ] }

Use the RegExp constructor to create a regular expression, two arguments: one is the string pattern to match, and the other is an optional flag string. Both of these parameters are strings!

Using regular expression literals is not the same as using regular expressions created with the RegExp constructor. In ECMAScript 3, regular expression literals always share the same regexp instance, and each new RegExp instance created with the constructor is a new instance. In ECMAScript5, however, both will create a new RegExp instance.

    1. RegExp Instance Properties:

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

IgnoreCase: Boolean value that indicates whether the I flag is set;

LastIndex: Integer that represents the character position at which to start searching for the next occurrence, starting from 0;

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

Source: A string representation of a regular expression that is returned in literal form rather than in the string pattern in the incoming constructor.

    1. RegExp instance method:

The Main method is exec (), which is specifically designed for capturing groups. EXEC () receives a parameter, which is the string to which the pattern is applied, and returns an array containing the first match information, or null if no match is found. The returned array is an instance of array, but contains two additional attributes: Index and input. In the case of the Exec () method, if the global flag is not set, calling exec () multiple times in the same string will always return the information for the first occurrence, and each call to exec () in the case of setting the global flag will continue to find the new match in the string.

The test () method receives a string parameter that returns true if the pattern matches the parameter, otherwise false.

The valueof () method of the regular expression returns the regular expression itself.

    1. When you use a function expression to define a function, there is no function name after it, and there must be a semicolon at the end of the function. A function name is simply a pointer to a function, so a function may have more than one name. Note that using the function name without parentheses is to access the function pointer, not the calling function.
    2. The difference between a function declaration and a function expression: The parser parses the function declaration first and makes it available (accessible) before executing any code, and as for the function expression, it must wait until the parser executes to the code where it resides before it is actually interpreted.
    3. Inside the function, there are two special objects: arguments and this. The main purpose of arguments is to save the function arguments, but it also has a property named Callee, which is a pointer to the function that owns the arguments object. The This object refers to the environment object to which the function is executed. The properties of another function object are defined in ECMASCRIPT5: caller. This property holds a reference to the function that called the current function. In strict mode, accessing the Arguments.caller property causes an error, and you cannot assign a value to the caller property of the function, or it can result in an error.
    4. Each function contains two properties: Length and prototype, where the length property represents the number of named arguments that the function expects to receive. For reference types in ECMAScript, Protorype is the real place where all of their instance methods are saved. In ECMAScript5, the prototype attribute stone is not enumerable, so it cannot be found using for-in.
    5. Each function contains two non-inherited methods: Apply () and call (). The purpose of both methods is to invoke the function in a specific scope, which is actually equivalent to setting the value of the This object in the function body.

The Apply () method receives two parameters: one is the scope in which the function is run, and the other is the parameter array. The second parameter can be an instance of an array, or it can be an arguments object.

The call () method is the same as the Apply () method, and they differ only in how the parameters are received. For the call () method, the first parameter is the this value does not change, changing the rest of the parameters are passed directly to the function. In other words, when you use Call (), the arguments passed to the function must be enumerated individually.

The most powerful part of apply () and call () is the ability to extend the scope in which functions are run. The benefit is that the object does not need to have any coupling with the method.

ECMAScript 5 also defines a method: Bind (). This method creates an instance of a function whose this value is bound to the value passed to the bind () function.

    1. 3 Special Reference types: Boolean, number, and string. The primary difference between a reference type and a basic wrapper type is the lifetime of the object. An instance of a reference type created using the new operator, which has been saved in memory before the execution flow leaves the current scope, and automatically creates an object of the basic wrapper type, the value exists in the execution moment of one line of code. Calling typeof on an instance of the base wrapper type returns "Object", and all objects of the basic wrapper type are converted to Boolean true. Note: Using new to invoke the constructor of the basic wrapper type is not the same as invoking a transformation function that has the same name (see book page 119 for example).
    2. The number type provides a way to format numeric values as strings: Tofix (), a string representation of the numeric value returned by the specified decimal place, and a rounding rule. The method used to format the numeric value is toexponential (), which returns the string form of the numeric value represented by the specified notation (e notation), receives the parameter, and specifies the number of decimal digits in the output result. For a numeric value, the Toprecision () method may return a fixed-size (fixed) format, or an exponential format, which also receives a parameter, which is the number of digits (not including the exponential portion) that represents the numeric value. All three methods can be rounded up or down to make the most accurate representation of the values with the correct decimal digits.
    3. Method of type String
      1. The character methods CharAt () and charCodeAt () receive one parameter, which is based on the 0 character position. A copy of the character that returns the specified position, and another character encoding that returns the specified position character;
      2. String manipulation: concat (), used to stitch together one or more strings, returning a new string of stitching.

Slice ()

SUBSTRING ()

SUBSTR ()

First parameter

Specify the starting position of the string

A second parameter

Specifies the position after the last character of the substring, if none to the end

Specifies the number of characters returned, if none to the end

Whether to modify the value of the string itself

Whether

parameter is negative

Will pass in a negative value with the length of the string think home

Convert all negative arguments to 0

The negative first argument is added to the length of the string, and the negative second argument is converted to 0

    1. The location method of the string:

IndexOf ()

LastIndexOf ()

Function

Searches for the given string from a string, then returns the position of the string, or 1 if not found

Difference

Search for substrings backwards from the beginning of a string

Search for substrings forward from the end of a string

    1. The trim () method, defined in ECMAScript5, creates a copy of a string, removes all whitespace from the predecessor and suffix, and then returns the result without affecting the original string.
    2. String-Case Conversion methods: toLowerCase (), Tolocalecase (), toUpperCase (), and toLocaleUpperCase ().
    3. Pattern matching method for strings

The match () method accepts only one parameter, either a regular expression or a RegExp object. Returns an array whose first item is a string that matches the entire pattern, after which each item (if any) holds a string that matches the capturing group in the regular expression.

The search () method receives only one parameter, either a regular expression or a RegExp object. Returns the index of the first occurrence in a string, or 1 if there is no match. The method always looks backward from the beginning of the string.

The replace () method accepts two parameters: the first argument can be a RegExp object or a string (the string is not converted to a regular expression), the second argument can be a string or a function, and the function accepts 3 arguments: pattern matches, The position of the pattern match in the string and the original string.

Split () splits a string into multiple substrings based on the specified delimiter and places the result in a set of arrays, either as a string or as a RegExp object (the string is not converted to a regular expression). The split () method can receive an optional second parameter that specifies the size of the array to ensure that the returned array does not exceed the specified size.

    1. The Localecompare () method compares two strings and returns one of the following values:

If the string should precede the string parameter in the alphabet, a negative number is returned (in most cases 1, depending on the case);

Returns 0 if the string equals the string argument;

If the string should be followed by a string parameter in the alphabet, an integer is returned (1 in most cases, depending on the case).

    1. The fromCharCode () method, which is a static method of the string constructor itself, accepts one or more character encodings and then converts them to a string. Essentially, this method performs the opposite operation with the instance method charCodeAt ().
    2. Two big monomer built-in objects: Global and math

The global (Global) object, properties and methods that are not part of any other object, are ultimately its properties and methods. The encodeURI () and encodeURIComponent () methods of the global object can encode URIs (Uniform Resource Identifiers, Universal Resource Identifiers) to be sent to the browser. where encodeURI () is used primarily for the entire URI, and encodeURIComponent () is used primarily to encode a segment of the URI. The difference is that encodeURI () does not encode special characters that are themselves URIs, such as colons, forward slashes, question marks, and well sizes, while encodeuricomponent () encodes any non-standard characters it discovers. The two methods corresponding to encodeURI () and encodeURIComponent () are decodeURI () and decodeURIComponent (), where decodeURI () can only be used for encodeURI () The substituted characters are decoded, in the same vein, decodeuricomponent () can only replace the encodeuricomponent () encoding, which is the encoding of any special characters.

The eval () method is the most powerful method in the ECMAScript language, like a full ECMAScript parser, that receives only one parameter, the ECMAScript (or JavaScript) string to execute. In strict mode, any variables or functions that are created outside of Eval () are not accessed externally.

The properties of the Math object are shown in page 134 of the book.

The min () and Max () methods of the Math object. Can receive any number of numeric parameters.

Rounding Method: Math.ceil () rounds up to the nearest integer, Math.floor () rounds down to the nearest integer, Math.Round () performs standard rounding, rounded to the nearest integer.

The random () method returns a random number greater than or equal to 0 less than 1.

JavaScript Advanced Programming (3rd Edition) Chapter Fifth 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.