A summary of common methods for JavaScript arrays and strings

Source: Internet
Author: User

Let's start with a code primer:

varStr='Hello World'; alert (Str.charat (1));//find values by subscript;Alert (Str.indexof ('W',3));//find the string subscript by value; no return-1 is found; there are two parameters (the second parameter can be no, and some words are searched from here);Alert (Str.charcodeat ('W'));//conversion Unicode encoding;Alert (String.fromCharCode (119));//to change the Unicode encoding to a specific valueAlert (Str.touppercase ());//Convert to uppercaseAlert (Str.tolowercase ());//Convert to lowercaseAlert (Str.split ("'));//separate arrayAlert (str.substring (0,4));//intercepts a string;Alert (Str.match (/\d+/g));//find the value in the string;Alert (/\d+/g.test (str));//see if the string matches the regular;vararr=[1,2,3,4,0];vararr1=[8,9];alert (Arr.join ("'));//The array is converted into a string;Alert (Arr.push ('5'));//add the following; The return value is the length of the new array;Alert (Arr.pop ());//After Deleting a value, the return value is the deleted valueAlert (Arr.unshift ('0','-1'));//Before adding, the return value is the length of the new array;Alert (Arr.shift ())//Before Deleting a value, the return value is the deleted valueAlert (Arr.sort ());//SortAlert (Arr.reverse ());//ReverseAlert (Arr.concat (ARR1));//concatenate two or more arrays, returning a new array without changing the value of the original arrayAlert (Arr.splice (1,2));//The return value is the deleted valueAlert (Arr.splice (1,2,'a'));//The return value is the deleted value, and the new array is inserted with A;//Splice (Start,deletecount,val1,val2,...): Deletes the DeleteCount item from the start position and inserts val1,val2 from that position,...Alert (arr);

One, array:

Push (): Adds one or more elements to the tail of the array, returning the length of the array after the new element is added. --Change the original array

Pop (): Deletes the last element of the array, returning the element that was deleted. --Change the original array

Unshift (): Adds an element to the first position of the array and returns the length of the array after the new element is added. --Change the original array

Shift (): Deletes the first element of the array and returns the element. --Change the original array

// shift () can traverse to empty an array var list = [123456]; var item;  while (item = List.shift ()) {  Console.log (item);} Console.log (list);      //  []

ValueOf (): Returns the array itself.

// the ValueOf () method can return the original value of a Boolean object.  varnew Boolean (0); b.valueof (); // false

IndexOf (): Returns the position of the specified element in the array, returns if it does not appear, -1 or the second argument, which indicates where the search begins.

ToString (): Returns the string form of the array. --Do not change the original array

var arr = [123, [456]];arr.tostring ();     // "1,2,3,4,5,6"

Join (): Returns all array members as a string, with a parameter as a delimiter. If no arguments are supplied, the default is separated by commas. --Do not change the original array

Concat (): Used for merging multiple arrays. It adds the members of the new array to the end of the original array, and then returns a new array, unchanged from the original array. --Do not change the original array

Reverse (): Used to reverse the order of the elements in the array, returning the changed array. --will change the original array

Sort (): Sorts the members of an array by default, sorted in dictionary order. After sorting, the original array is changed to return the changed array. --will change the original array

[101].sort ();    // [101, all] [101111101111].sort ();   // [10111, 1101, 111]

   Special attention is required: sort The method is not sorted by size, but by the dictionary order of the corresponding string. That is, the values are first converted to strings and then compared in dictionary order, so they are 101 in 11 front of each other.

If you want sort the method to be ordered in a custom manner, you can pass in a function as an argument, which means sorting by custom method. The function itself accepts two parameters, representing two elements for comparison. If the return value 0 is greater than, indicates that the first element is followed by the second element, and in other cases, the first element is preceded by the second element.

vararr = [10111,1101,111];arr.sort (function (A, b) {returnAb;})//[111, 1101, 10111]varARR1 =[{name:"Zhang San", Age: -}, {name:"John Doe", Age: -}, {name:"Harry", Age: -}];arr1.sort (function (O1, O2) {returnO1.age-o2.age;}) // [//{name: "John Doe", age:24},//{name: "Harry", age:28},//{name: "Zhang San", age:30}// ]

Slice (): Used to intercept part of the original array, return a new array, the original array unchanged. --Do not change the original array

Usage: Slice (start,end)

(1) Its first argument is the starting position (starting at 0) and the second parameter is the terminating position (but the element itself is not included in the position ). If the second argument is omitted, it is returned to the last member of the original array.

(2) The parameter is negative, then the position of the reciprocal calculation;

(3) No parameter, returns the array itself.

vararr = ['a','b','C'];arr.slice (1,2)//["B"] the second parameter itself does not contain aArr.slice ()//["A", "B", "C"] no parameter returns the original arrayArr.slice (-2)//["B", "C"] parameter is negative, which means the position of the reciprocal calculationArr.slice (-2, -1)//["B"]

Splice (): Deletes a member of the original array and can be added to the new array member at the deleted location, and the return value is the deleted element. --Change the original array.

Usage: Splice (start,delnum,addelement1,addelement2,...)

(1) The first parameter is the starting position of the deletion, and the second parameter is the number of elements to be deleted. If there are more arguments later, it means that these are the new elements to be inserted into the array.

(2) If only the element is inserted, the second parameter can be set to 0. (When the third number is not written, the equivalent of delete function!) When the second argument is 0 o'clock, it is equivalent to adding a function! )

(3) If there is only the first argument, then all subsequent elements are deleted, equivalent to splitting the original array into two arrays at the specified position

(4) when deleted, two parameters, the first one is the start position, the second is the deletion length. When inserting, three parameters, the first one is the insertion position (inserted before), the second is 0, and the third is the inserted content. When replaced, three parameters, the first one is the start position, the second is the deletion length, and the third is the replacement content.

vararr = [1,1,1];arr.splice (1,0,2)//[] If only the element is inserted, the second parameter can be set to 0Console.log (arr)//[1, 2, 1, 1]vararr = [1,2,3,4];arr.splice (2)//[3, 4] If only the first argument is equivalent to splitting the original array into two arrays at the specified positionConsole.log (arr)//[1, 2]

Map (): All members of an array call a function in turn, returning a new array based on the result of the function. --Do not change the original array

var numbers = [123];numbers.map (function (n) {  return  1;});       // [2, 3, 4]numbers;      // [1, 2, 3]

Filter (): The parameter is a function in which all array members execute the function sequentially, returning the returned result as true a new array of members. --Do not change the original array

var arr = [12345]arr.filter (function (elem) {     return 3 );}); // [4,5]console.log (arr)//[1,2,3,4,5]

Second , the string:

charAt: Returns a string at the given position of the string.

concat: Connect 2 strings. The original is unchanged.

SUBSTRING, substr, slice can omit the second argument, which means it lasts until the end of the string.

Trim: removes whitespace from both ends, without affecting the previous string. (Half-width full-width space, Chinese and English Spaces, TAB key eradication)

toLowerCase, toUpperCase: to the case, the original unchanged.

indexOf, lastIndexOf: determines the first occurrence of a string in another string, one starting from the head and one starting from the tail.

They can also accept the second parameter, for IndexOf, to start backward matching from that position, and for LastIndexOf, to indicate a forward match from that position.

Split: The string is cut by character, and the result returns an array without changing the original string.

var " ABC " ; S.split ("); // is empty, the conversion is to an array ["A", "B", "C"]
var s = "Abcd,ef";
s.split (', '); ["ABCD", "EF"

substring (Index of Start position, end End position Index): (1) The position of the intercept does not contain the end position of the character, (2) write only one parameter to intercept from the beginning to the end, (3) to enter a negative value into 0, which is smaller as the starting position.

var " ABCDE " ; str.substring (2); // CDEstr.substring (1,3); // BCstr.substring (-2,2); // abstr.substring (3,1); // BC

Slice (Start position index, end end position index): Basic and substring similar, difference in parameter is negative.

Enter a negative value to add to the length of the string

Http://www.jb51.net/article/102964.htm

Third , number:

ToFixed (): The decimal is reserved and the result is a string type.

var 1.1262 ; a.tofixed (2); // 1.13, calculated by rounding, the result is a string type

Parseint and parsefloat: string to numeric type

Number to character toString or number + ""

A summary of common methods for JavaScript arrays and strings

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.