JavaScript reading notes (5)-array REGEXP

Source: Internet
Author: User
Tags character classes

1. Array type

Each item of the ECMAScript array can hold any type of data, and the size of the array can be dynamically adjusted;

(1) Creating an array

First method: Array constructor

  var colors=new Array ();

var colors1=new Array (20);

var colors2=new Array ("Rad", "Blue", "green");

var colors3=array (3);

var colors4=array ("Greg");

Second way: Array literals

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

var names=[];

When using the array literal notation, the array constructor is not called;

(2) Reading and setting arrays

When reading and setting array values, use square brackets and provide a 0-based numeric index of the corresponding values;

When you set the index of a value that exceeds the number of existing entries in the array, the array is automatically incremented to the length of the index value plus 1;

The length property of an array is not read-only, and with 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[99]= "BLACK";

alert (colors.length); 100

Alert (colors[3]); Undefined

(3) Detecting arrays

First type: instanceof operator

  if (value instanceof Array) {//Some operations on an array}

Instanceof assumes a single global execution environment, if there are multiple frames in the Web page, there are more than two different global execution environments, there are more than two different versions of the array constructor;

Second type: Array.isarray () method (ECMAScript5 new)

Determines whether a value is an array, regardless of the global execution environment in which it was created;

(4) Conversion method

The ToString () method returns a comma-delimited string of strings for each value in the array;

ValueOf () returns an array;

The toLocaleString () method also returns a comma-delimited string of array values, but invokes the toLocaleString method for each item;

Using the Join method, you can use a different delimiter to construct a string, accepting only one parameter, which is used as a delimited string;

If an item value in an array is null or undefined, the value is represented by an empty string in the above method;

(5) Stack method (LIFO)

ECMAScript provides a push and pop method for implementing a stack-like behavior for arrays;

Push can accept 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 returns the removed item;

(6) Queue method (FIFO) Push and Shift methods

The shift method moves the first item in the array and returns the item, with the length minus 1;

The Unshift method adds a person to an item in the front of the array and returns the length of the new array.

(7) Reorder method

The reverse method reverses the order of the array items;

The sort method arranges the array items in ascending order, and the sort method invokes the ToString transformation method of each array item, and then compares the resulting string to determine how to sort, even if each item in the array is a numeric value, and the Sort method compares the string;

  var values=[0,1,5,10,15];

Values.sort ();

alert (values); 0,1,10,15,5

The Sort method can accept a comparison function as a parameter so that we make that value in front of that value

  function Compare (value1,value2)

{

if (value1<value2) {return-1;}

else if (value1>value2) {return 1;}

Else{return 0;}

}

Values.sort (Compare); 0,1,5,10,15

For numeric types, the Compare function is simpler

  function Compare (value1,value2)

{

Return value1-value2;

}

(8) Operation method

Concat method: Based on the current array of all items in a new array, it will first create a copy of the current array, and then add the received parameters to the end of the copy, and finally return the newly constructed array, in the absence of parameters, just return a copy of the current array, if the parameter one or more arrays, Each item in the array is added to the result array, and if the value passed is not an array, the values are simply added to the end of the result array;

The slice method, which creates a new array based on one or more items in the current array, returns all items starting at the specified position of the parameter to the end of the current array, and if there are two parameters, the method returns the entry between the starting and ending positions (but not the item at the end). The slice method does not affect the original array;

If the parameter of the slice method has a negative number, the corresponding position is determined by the length of the array, and the call to Slice ( -2,-1) on an array containing 5 items is the same as the result of invoking slice (3,4);

Splice method: Mainly inserts an item into the middle of the array

Delete: You can delete any number of items, requiring only two parameters: the position of the first item to be deleted and the number of items to be deleted, such as splice (0,2), will delete the first two items in the array;

Insert: You can insert any number of items to the specified location, you need to provide only 3 parameters: Start position, 0 (number of items to delete) and the item to insert, if you want to insert more than one item, you can pass in four, five, and any number of items;

Replace: You can insert any number of items to the specified location, and delete any number of items at the same time by specifying 3 parameters, starting position, number of items to be deleted, and any number of items to insert, the inserted item does not have to be equal to the number of items deleted;

The Splice method always returns an array that contains the items removed from the original array (an empty array is returned if no items are deleted);

(9) Location method

Both the IndexOf and the LastIndexOf methods receive two parameters: the subparagraphs (optional) to find indicates the index at which to find the starting position;

The IndexOf method starts looking backwards from the beginning of the array (position 0), and Lasrindexof looks forward from the end of the array;

(10) Iterative method

ECMASCRIPT5 defines 5 iterative methods for an array, each of which accepts two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this, the function passed in these methods receives 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: Each item in an array runs the given function, with no return value;

Map: Each item in an array runs the given function, and returns a list 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;

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

var filterresult=numbers.filters.filter (function (Item,index,array) {

Return (ITEM>2)

})

Alert (Filterresult); [3,4,5,4,3]

(11) Reduction method

ECMAScript5 added two ways to reduce arrays: reduce and reduceright, all of the items of the algebraic group are iterated, and then a value is constructed that is ultimately returned; reduce starts from the first item in the array, and then iterates through the Reduceright, starting with the last item in the array, traverses forward to the first item;

Both methods receive two parameters: a function that is called on each item and (optionally) as the initial value for narrowing, and the function receives 4 parameters: the previous value, the current value, the index of the item, and the array object; any values that this function puts back are automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first parameter is the first item in the array. The second parameter 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+cur;

});

Alert (sum); 15

2. RegExp type

(1) Literal forms define regular expressions

Create regular expression: var expression=/pattern/flags;

Pattern can be any simple and complex regular expression that can contain character classes, qualifiers, groupings, forward lookups, and reverse references; flags are used to indicate that the regular expression behaves mainly as follows:

G: Global mode, the pattern will be applied to all strings, not immediately stop when the first match is found;

I: case insensitive mode;

M: multi-line mode;

var pattern=/.at/gi; Matches all combinations of 3 characters ending with "at", not case-sensitive;

Metacharacters must be escaped, and metacharacters include:

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

Var pattern2=/\[bc]at/i; Match first "[Bc]at", Case insensitive

(2) RegExp form of the constructor function

The constructor receives two parameters: one is the string pattern to match, and the other is the optional flag string;

Var pattern2=new RegExp ("[Bc]at", "I");

The string pattern has double escaping in some cases, the literal pattern:/\[bc\]at/equivalent string is: "\\[bc\\]at"

In ECMAScript3, the same regexp instance is shared in the regular expression literal, and every new RegExp instance created with the constructor is a new instance;

ECMAScript5 explicitly stipulates that the use of regular expression literals must create a new RegExp instance every time, just as the ECMAScript3 constructor is called directly;

(3) RegExp instance Properties

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

IgnoreCase: Boolean value, whether the I flag is set

LastIndex: Integer that starts searching for the next occurrence of the character position, starting from 0

Multiline: Boolean value, whether the M flag is set

Source: The regular expression string representation, returned in literal form instead of the total string pattern of the passed-in constructor;

(4) RegExp instance method

First method: Exec ()

The Exec method takes a parameter, which is the string to which the pattern is applied, returns an array containing the first match information, returns NULL if there is no match, and returns an array instance, but contains two additional attributes: Index and input, Index represents the position of the match in the string, input represents the string to which the regular expression is applied, in the array, the first item is a string that matches the entire pattern, and the other item is a string that matches the capturing group in the pattern (if there is no capturing group in the pattern, the array contains only one item);

In the Exec method, even if the global flag (g) is set, only one match is returned at a time, and calling exec multiple times on the same string without setting the global flag will always return the information for the first occurrence, and in the case of setting the global flag, the new match will continue to be found in each invocation of the string;

A second method: Test ()

The test method accepts only one parameter, returns true if the pattern matches the parameter, otherwise returns false;

(5) RegExp constructor properties (these properties are considered static properties in other languages)

Long attribute names:input, Lastmtach, Lastperson, Leftcontext, multiline, Rightcontext

Short attribute name:$_ $& $+ $ ' $* $ '

Input returns the original string

Leftcontext returns a string before matching a word

Rightcontext returns a string after matching a word

Lastmtach returns the most recent string that matches the entire regular expression

Lastperson returns the most recent matching capture group

JavaScript reading notes (5)-array REGEXP

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.