Introduction to JavaScript arrays and string usages

Source: Internet
Author: User
Tags constructor prev

One, array

(1) Detection array

For a global scope, you can use the instanceof operator to detect whether an object is an array:

The code is as follows Copy Code
if (value instanceof Array) {
//
}


However, if there are multiple frames in a Web page, there are actually several different global scopes, so there are several different versions of the array constructor. If you pass an array to another frame from one frame, the above operator does not work. ES5 the new Array.isarray () method can determine whether an object is an array, regardless of which global scope it was created in.

The code is as follows Copy Code

if (Array.isarray (value)) {
//
}

Here's an example:

The code is as follows Copy Code

<script Language = "JAVAScript" >
<!--
var fruit; Declaring an array (variable)
Fruit = ["Watermelon", "banana", "apple"]; Assign values to three of fruits in an array
The first time the 3 variable contents of the array "fruit" are displayed,<br> is a newline character
document.write (Fruit[0] + "<br>" + fruit[1] + "<br>" + fruit[2] + "<br>" + fruit);
document.write ("Fruit = [fruit[0],fruit[1], "grass mold"]; Change the variable "fruit[2]" in the "fruit" array as "Trichoderma"
The second display of the 3 variable contents of the array "fruit",<br> is a newline character
document.write (Fruit[0] + "<br>" + fruit[1] + "<br>" + fruit[2] + "<br>" + fruit);
document.write ("Fruit = ["Watermelon", "grass mould"]; To assign a value to a variable in the array "fruit"
The third display of the 3 variable contents of the array "fruit",<br> is a newline character
document.write (Fruit[0] + "<br>" + fruit[1] + "<br>" + fruit[2] + "<br>" + fruit);
document.write ("Fruit = ["Watermelon", "banana",,]; To assign a value to a variable in the array "fruit", to increase the array to 4 variables
Fourth time to display the 4 variable contents of the array "fruit",<br> is a newline character
document.write (Fruit[0] + "<br>" + fruit[1] + "<br>" + fruit[2] + "<br>" + fruit[3] + "<br>" + Fru IT);
document.write ("-->
</Script>


(2) Conversion method

So objects have the ToString (), valueof () method. The call to the ToString () method of the array returns a comma-delimited string of strings of each value in the array.

And the call to the valueof () method returns an array.

Using the Join () method, you can use a different separator to build a string converted by an array. It takes a string argument and uses it as a separator. The default is a comma. If passed in, the array is not spliced together, as with the string's + operation.

(3) Stack, queue method

Push (): Receives any number of arguments, adds them to the end of the array one by one, and returns the length of the modified array.

Pop (): Moves the last item of the divisor group without parameters and returns the item.

Shift (): Removes the first item of the divisor group and returns the item without parameters.

Unshift (): Receives any number of arguments, adds to the front of the array, and returns the length of the new array.

(4) Reordering methods

Reverse (): Reverses the order of the array items and returns the modified array.

Sort (): Arranges the array items in ascending order by default and returns the sorted array. It invokes the ToString () method for each item, and then compares the resulting string, even though each entry in the array is a number.

The code is as follows Copy Code
var num = [0,1,5,10,15];
Num.sort ();
Console.log (num); [0,1,10,15,5]

Because of this, we generally pass a comparison function as an argument to sort ():

The code is as follows Copy Code
function Compare (value1, value2) {
if (value1 < value2) {
return-1; This is in ascending order. You can swap-1 and 1 to make the result descending.
else if (value1 > value2) {
return 1;
} else {
return 0;
}
}

If you return an object type of a numeric type for a numeric type or other valueof () method, you can use the following simpler comparison function:

The code is as follows Copy Code

function Compare (value1, value2) {
return value1-value2; This is in ascending order. You can exchange value1 and value2 to make the results descending.
}

(5) Operation method


The split () method is used to split a string into an array of strings.


Concat (): Creates a copy of the current array, adds parameters to the end of the replica, and returns the newly constructed array. (That is, the original array does not change)

Slice (): accepts one or two arguments, that is, to return the starting and ending positions of the items (the items at the end are not returned). When there is only one argument, all items from the starting entry to the end of the current array are returned. (the original array does not change)

Splice (): The main purpose is to insert items into the middle of the array. (returns an array of items that are deleted from the original array, or an empty array), as in 3 cases:

1. Delete: 2 parameters, the position of the first item to be deleted, and the number of items to delete. Splice (0,2) deletes the first two items in the array.

2. Insert: 3 (or more) parameters, starting position, 0 (number of items to delete), any items to insert. Splice (2,0, ' Insert ') position 2 of the former array insert item ' Insert ' (note ' Insert ' is the first

2 items rather than 3rd).

3. Replace: 3 (or more) parameters, starting position, number of items to delete, any items to insert. Splice (2,1, ' red ', ' green ') deletes the entry for position 2, inserting the specified item from position 2.

(6) Location method

IndexOf (): Two parameters, Xiang (optional) that represents the index of the location where the start of the lookup is to be found. Find from left to right.

Lastindesof (): Ditto, the difference is to look from right to left.

Both methods return the position of the item to find in the array, and return-1 if it is not found.

The code is as follows Copy Code
var num = [1,2,3,4,5,4,3,2,1];
Alert (Num.indexof (4)); 3
Alert (Num.lastindexof (4)); 5

Alert (Num.indexof (4,4)); 5
Alert (Num.lastindesof (4,4)); 3

(7) Iterative method

ES5 defines 5 iteration methods for an array. Each method accepts two parameters: the function to run on each item and (optionally) the scope that runs the function-affects this value.

The functions passed into these methods receive 3 parameters: The value of the array item, the item's subscript in the array, and the array object itself.

Every (): Runs the given function for each item in the array, and returns true if each entry returns TRUE.

Some (): Runs the given function for each item in the array, and returns true whenever any entry returns TRUE.

Filter (): Each item in an array runs the given function, returning an array of items that the function returns True.

ForEach (): Each item in the array runs the given function, and no return value is returned.

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

(8) Merging method

ES5 adds two methods for merging arrays: reduce (), reduceright (). The two methods iterate over all the items of the group and then build a value that is eventually returned.

The reduce () method starts with the first item of the array, Reduceright () instead.

They all receive two parameters: the function called on each item, optionally, as the initial value of the merge base.

The function passed in receives 4 parameters: the previous value, the current value, the index of the item, and the array object.

The code is as follows Copy Code
var num = [1,2,3,4,5];
var sum = num.reduce (function (Prev,cur,index,array) {
The return value of this function is automatically passed to the next item as the first argument. Here, the first iteration: Prev is 1,cur is 2.
For the second iteration, the Prev is 3 (the 1+2 result), and the Cur is 3.
return prev + cur;
});
alert (sum); 15

Second, string

(1) Character method

CharAt (): receives a parameter representing the position of the character.     var str = ' Hello ';  Alert (Str.charat (1)); E

charCodeAt (): Parameter ibid. Gets not the character but the character encoding.     var str = ' Hello ';  Alert (Str.charcodeat (1)); ' 101 '

You can also use square brackets to add an index to visit: var str = ' Hello '; Alert (str[1]); E

(2) String manipulation method (the following methods do not affect the original string)

Concat (): similar to array. In practice more is to use +.

Slice (): 2 parameters represent the start position of the substring, the ending position (not included in the substring).

SUBSTRING (): ditto.

SUBSTR (): The first argument is the same, and the second parameter represents the number of characters returned.

If you do not have the 2nd argument, the length of the string is the end position.

(3) String position method

IndexOf (): Refer to the array above.

Lastindesof (): Refer to the array above.

(4) Trim () method: Creates a copy of the string, deletes all the spaces of the front and suffix, and returns the result.

(5) Case conversion

toLowerCase (), toLocaleLowerCase (), toUpperCase (), toLocaleUpperCase ().

(6) Pattern matching method (to be added)

Match ()

Search ()

Replace ()

Split ()

(7) Localecompare () method

This method compares two strings and returns the following values:

If the string should precede the string parameter in the alphabet, return a negative number (-1) and, after that, return a positive number (1) and an equal return of 0. (in different regions, the methods behave differently.) If the country is different. )

The code is as follows Copy Code
var str = ' Yellow ';
Str.localecompare (' brick '); 1
Str.localecompare (' yellow '); 0
Str.localecompare (' Zoo '); -1

(8) fromCharCode ()

This is a static method of the string constructor. Receives one or more string encodings and converts them to a string. The opposite operation is performed with charCodeAt ().

  code is as follows copy code

String.fromchar Code (104); ' H '

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.