JavaScript frequently uses object Array (2)

Source: Internet
Author: User

    • Join method for arrays
    • Array stitching concat method
    • Array Segmentation Slice Method
    • A powerful splice approach
    • IndexOf and LastIndexOf methods
    • Several frequently used iterative methods
Join method for arrays

We know that the ToString () and toLocaleString () methods of the array return a comma-delimited array string. But suppose we want the delimiter to be not a single comma, we can choose to use the Join () method. The join () method can accept a parameter, which is the delimiter we want, such as:

var colors = ["red", "blue", "white"];alert(colors.join("?"));

Will get:

red?blue?white

Suppose you do not specify a number of parameters for the Join () method:

alert(colors.join());

A comma is used as the delimiter by default:

red,blue,white
Array stitching concat method

We know that in the operation method of the string. The Concat () method, which is used for string concatenation, has the same method used for concatenation of arrays in arrays.

JS and Java and other languages a significant difference is that in Java and other languages when calling a function, the parameters of the incoming function must be strictly consistent with the previously created function signature.

In JS, the parser will not only check the data type of the incoming parameters, even the number of the input in a few, regardless. When using the Concat () method, we are able to:

Pass in one or more arrays as a parameter. The Concat () method first creates a copy of the original array, then joins the array passed in as a parameter to the end of the new array, and finally returns the copy.

Passing in one or more non-array values as a parameter, the Concat () method will first create a copy of the original array and then manipulate the copy. Add the passed-in value to the end of the copy, and then return.

Pass in a combination of one or more arrays and values, as in the previous procedure.

In fact, JS does not require the input parameter data type, the number of parameters, the same time JS in the elements between the array can be different.

The Concat () method is in fact able to accept one or more arbitrary types of parameters to implement the concatenation of arrays. Although it is very often not necessary to do so.

Personally think this is JS to give us the freedom, but how to make good use of this is not easy.

It is important to note that the concat () method does not alter the original array, but instead creates a copy of the original array, operates on the copy, and returns the new array as the return value.

To give a more extreme example:

function  test   ()  {   var  arr = []; var  colors = [ "Red" ,   "Blue" ,  "white" ]; var  hello = function    ()  { alert ( "Hello world!" ); arr = Arr.concat (colors, false , 1 , undefined , " yellow ", [" Gray "  , ], hello);   Alert (arr);} 

The above code we use the Concat () method of the array. After the empty array, arr, is stitched in turn 数组colors Boolean型false . 数值型1, Undefined type, String型yellow . 数组["gray, "black"]and a function.

The above code output is for example:

Array Segmentation Slice Method

The slice () method is used to cut out the specified interval of an array. It is capable of accepting 1 or 2 of the parameters. These two parameters specify the starting and ending position of the slice.

When only one argument is passed in. Returns an array of the position to the end of the array.

When two parameters are passed in, put back the first sub-array to the second parameter interval. (elements that do not include the second parameter position)

Say:

function test() {  var colors = ["red""blue""white""gray""green""gold""orange"];  var col1 = colors.slice(2);  var col2 = colors.slice(14);  "\n""\n" + col2);}   

Output:

We can see that the slice () method does not change the value of the original colors array, and the same time the segmented array does not include the corresponding entry for the second parameter.

The slice () method passes in a negative number, and the negative meaning is the offset from the end. The location is determined by adding the length of the array and the number of references. For example, when the number of team leader length is 10 cases. Slice (-3. -1) and Slice (7, 9) are equivalent.

It is also necessary to note that the second parameter is less than the first one. The method returns an empty array.

A powerful splice approach

The splice () method removes the specified item from the array and inserts the specified item at the specified position in the array.

Or the Combine delete and insert operations evolve to replace the specified item at the specified location.

Delete the specified item

The splice () method now accepts two parameters. The first parameter specifies the starting position of the deletion, and the second parameter designates the number of items that need to be deleted. The method returns an array of deleted items. If the item is not deleted, an empty array is returned.

function test() {  var colors = ["red""blue""white""gray""green""gold""orange"];  var col1 = colors.splice(13);  "\n" + col1);}

Output:

Insert specified item

The specified item to insert in the array. The splice () method needs to accept 3 parameters, and the first parameter specifies the starting position of the insertion. The second is the number to delete (we set this to 0.) That is, no matter what item is removed, the third parameter is the item to be inserted.

Like what:

function test() {  var colors = ["red""blue""white""gray""green"];  var col1 = colors.splice(10"brown""orange");  "\n" + col1);}

Output:

The col1 is now an empty array.

Replace the specified item

As a matter of fact. In an operation that inserts a specified item, the second parameter is set to a value other than 0 to remove some items and then insert the specified item at that point, which completes the replacement function.

IndexOf and LastIndexOf methods

The functionality of both methods is to find the location of the specified item in the array.

They all accept one or two of the parameters. The second number of parameters is optional.

The first of these parameters specifies the item to be found, and the second parameter specifies the starting position of the lookup. Just the IndexOf method looks backwards from the array's head, and the LastIndexOf method looks forward from the end of the array.

When the lookup is successful. Returns the matching position, otherwise returns-1.

It is important to emphasize that the search for success here needs to be congruent with the specified item (= = =) instead of "= =".

To give a simple example:

  var colors = ["red""blue""gray""white""gray""blue""red"];  var ind1 = colors.indexOf("gray");  var ind2 = colors.indexOf("gray"3);  var ind3 = colors.lastIndexOf("gray");  var ind4 = colors.lastIndexOf("gray"3);

The above code, IND1 equals 2,ind2 equals 4,ind3 equals 4. Ind4 equals 2.

Several frequently used iterative methods

In JS, it is easier to implement the method of array iteration. Each of the 5 iteration methods described below receives one or two parameters. The first parameter specifies the function to execute on each item of the array, the second parameter is not required, and the scope object that executes the function is specified.

The function in which each item of the array is to be applied receives 3 parameters: The value of the array item. The position of the item in the array and the array itself. That's very abstract, look at the following example:

    • The primary array for each of these traversal operations, we can use the foreach () method (similar to a for loop in very many other languages). The method has no return value. If you add 1 to each item in the array:
var num = [1234567];varfunction(item, ind, array) {  array1;}var rst = num.forEach(forfun);alert(num);

Get the following output:

    • Suppose we want to check if every item in the array satisfies a condition that can use the every () method, only returns ture if all the items in the array satisfy the condition, or false.
var num = [1234567];varfunction(item, ind, array) {  return3)。}var rst = num.every(everfun);

The code above will check if each item in the array is greater than 3. The Every () method returns true only if every item in the array satisfies a condition.

It is clear that the above example returns FALSE.

    • Suppose we want to detect if there are certain items in the array that satisfy a certain condition to be able to use the some () method. Unlike every (), returns True when there are certain items in the array that satisfy a condition.
var num = [1234567];varfunction(item, ind, array) {  return3);}var rst = num.some(somefun);

An entry with an array greater than 3 exists, and the RST value returns TRUE.

    • Suppose we want to filter an item in an array that satisfies a certain condition, and can use the filter () method. The method returns a new array of items that satisfy the condition in the array (the item that returns True).
var num = [1234567];varfunction(item, ind, array) {  return3);}var"\n" + rst);

will get the following output:

1,2,3,4,5,6,74,5,6,7
    • Suppose we want to do some kind of mapping operation on an array, that is, each item in the array is given a total operation and the result of the operation is returned, using the map () method. For example, we can map an array to a truth table that is greater than 3:
var num = [1234567];varfunction(item, ind, array) {  return3);}var"\n" + rst);

Get the following output:

JavaScript frequently uses object Array (2)

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.