JavaScript: Array-type full parsing _ basic knowledge

Source: Internet
Author: User
The following small series will bring you a JavaScript: Comprehensive Analysis of the Array type. I think it is quite good. Now I will share it with you and give you a reference. Let's take a look at the array types in JavaScript with arrays in other languages. Each item in JavaScript can save any type of data.In addition The size can be dynamically adjusted. It can automatically increase as data is added to accommodate new data..

There are two basic methods to create an array.

1. Array Constructor

var cities = new Array();

If you know the number of projects to be saved in advance, you can also pass the number to the constructor. The number will automatically become the value of the length attribute.

var cities = new Array(3);

You can also pass the items in the Array to the Array constructor.

var cities = new Array("shanghai", "beijing", "shenzhen");

When creating an array, You can omit the new operator:

Var cities = Array (3); // create an Array containing three elements

2. array literal representation

Array literal representation is represented by a pair of square brackets containing array items. Multiple array items are separated by commas, as shown below:

Var cities = ["shanghai", "beijing", "shenzhen"]; var cities = []; // create an empty string

When reading and setting the array value, use square brackets and provide the corresponding value based on 0 (based on 0 is counted from 0, the first item is 0, the second item is 1, and so on), as follows:

Var cities = ["shanghai", "beijing", "shenzhen"]; alert (cities [0]); // "shanghai" cities [1] = "hongkong "; // modify the second item "beijing" to "hongkong" cities [3] = "taiwan" // Add one

The number of items in the array is stored in the length attribute,It is not read-only. Therefore, you can remove items from the end of the array or add new items to the array by setting the length attribute.

var cities = ["shanghai", "beijing", "shenzhen"];cities.length = 2;alert(cities[2]);  // undefined

This attribute of length can be used to add a new item at the end of the array:

var cities = ["shanghai", "beijing", "shenzhen"];cities[cities.length] = "hongkong";

1. detection array

ECMAScript5 adds the Array. isArray () method to determine whether a value is an Array, regardless of which global execution environment it is created. The usage is as follows:

If (Array. isArray (value) {// perform some operations on the Array}

2. Conversion Method

All objects have toLocaleString (), toString (), and valueOf () methods. The toString () method of the array is called to return a comma-separated string consisting of strings of each value in the array. For example:

var cities = ["shanghai", "beijing", "shenzhen"];alert(cities.toString());  // shanghai,beijing,shenzhenalert(cities.valueOf());  // shanghai,beijing,shenzhenalert(cities);       // shanghai,beijing,shenzhen

Note: Because alert () needs to receive string parameters, it will call the toString () method in the background, so it will get the same result of directly calling the toString () method.

In addition, the toLocaleString () method often returns the same value as toString () and valueOf (). The difference is that in order to get the value of each item,The toLocaleString () method of each item is called.Instead of the toString () method. For example:

var p1 = {    toLocaleString: function () {      return "p1 toLocaleString";    },    toString: function () {      return "p1 toString";    }  };  var p2 = {    toLocaleString: function () {      return "p2 toLocaleString";    },    toString: function () {      return "p2 toString";    }  };  var p = [p1, p2];  alert(p);  alert(p.toString());  alert(p.toLocaleString());

The result shows that the toString method is called in the first and second rows, and the toLocaleString method is called in the third row.

The toLocaleString (), toString (), and valueOf () methods inherited by the array are returned by default in the form of comma-separated strings. Using the join () method, you can use different characters to split the string and return a string containing all array items.

var cities = ["shanghai", "beijing", "shenzhen"];alert(cities);     // shanghai,beijing,shenzhenalert(cities.join(","));// shanghai,beijing,shenzhenalert(cities.join("|"));// shanghai|beijing|shenzhen

3. Stack Method

Stack is a kind of Data Structure of LIFO. The insertion and removal of data items in the stack can only happen at the top of the stack. The JavaScript Array provides the push () and pop () methods for Stack-like behavior.

Push () method

You can receive any number of parameters, add them to the end of the array, and modify the length of the array.

var params = new Array();var count = params.push("a", "b");alert(params); // a,balert(count);  // 2

The preceding example shows the number of inserted items returned by the push () method.

Pop () method

Remove the last entry from the end of the array to reduce the length of the array and return the removed entry.

var params = new Array();var count = params.push("a", "b", "c");var item = params.pop();alert(item);  // calert(params.length);  // 2

4. Queue Method

The access rule for the data structure of the queue is FIFO, that is, adding items from the end of the queue and removing items from the front-end of the queue.

Shift () method

The shift () method is provided in JavaScript to remove the first entry in the array and return the entry. At the same time, the length attribute of the array is modified.

Var params = new Array (); var count = params. push ("a", "B", "c"); var item = params. shift (); // obtain the first alert (item); // aalert (params. length); // 2

Unshift () method

JavaScript also provides the unshift () method, which can add any item on the front end of the array and return the length of the new array.

var params = new Array();var count1 = params.unshift("a");alert(count1); // 1alert(params); // avar count2 = params.unshift("b");alert(count2); // 2alert(params); // b,avar count3 = params.unshift("c", "d");alert(params); // c,d,b,a

It is observed that if one unshift () contains multiple items, it inserts these items into the array in order, that is, the first parameter is inserted at the beginning. As in the preceding example, "a" is inserted for the first time, "B" is inserted at the beginning of the array, and "B" is inserted for the second time. For the third time, there are multiple numbers, but the order is c before and d after.

5. Re-sorting method

The array provides two methods for directly re-sorting.

Reverse () method

The reverse () method reverses the order of array items.

var values = [1,2,3,4,5];values.reverse();alert(values); // 5,4,3,2,1

Sort () method

By default, the sort () method arranges array items in ascending order. To achieve sorting,The sort () method calls the toString () transformation method of each array item, and then compares the obtained string.Therefore,The sort () method compares strings..

var values = [3,5,53,2,34];values.sort();alert(values); // 2,3,34,5,53

However, we can say that such sorting is meaningless, and we need to sort the values.The sort () method can receive a comparison function as a parameter.To specify the sorting rules.

The comparison function receives two parameters. If the first parameter is located before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is placed after the second parameter, a positive number is returned.

function compare(value1, value2) {  if (value1 < value2) {    return -1;  } else if (value1 > value2) {    return 1;  } else {    return 0;  }}var values = [3,5,53,2,34];values.sort(compare);alert(values); // 2,3,4,34,53

6. Operation Method

Concat () method

You can create a new array based on all the items in the current array. This method creates a copy of the current array, adds the parameter to the end of the copy, and returns the newly constructed array. If one or more arrays are passed to the concat () method, each item in the array is added to the array.

var arrays = ["a", "b", "c"];var arrays2 = arrays.concat("d", ["e", "fe"]);alert(arrays); // a,b,calert(arrays2); // a,b,c,d,e,f

Slice () method

Creates a new array based on one or more items in the current array. The slice () method can receive one or two parameters, that isStart of the item to be returnedAndEnd position. If there is only one parameter, all items from the Start entry to the end of the array are returned. If there are two parameters, the items between the start position and the end position (excluding the end items) are returned ).The slice () method does not affect the original array.

var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];var cities2 = cities.slice(1);var cities3 = cities.slice(1,3);alert(cities2); // shanghai,shenzhen,guangzhou alert(cities3); // shanghai,shenzhen

Splice () method

The splice () method is mainly used to insert items into the middle of the array. There are three ways to use it:

• Delete any number of items. specify two parameters: the first item to be deleted and the number of items to be deleted. For example, splice (2nd) deletes items, 3, and 4 in the array.

var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];cities.splice(1,3);alert(cities); // beijing

• Insert can insert any number of items to a specified position. Specify three parameters: Start position, 0 (number of items to be deleted), and the item to be inserted

var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];cities.splice(1,0,"hongkong");alert(cities); // beijing,hongkong,shanghai,shenzhen,guangzhou

• Replacement can replace the items at the specified position. Specify three parameters: Start position, item to be deleted, and any item to be inserted.

var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];cities.splice(1,2,"hongkong");alert(cities); // beijing,hongkong,guangzhou

7. Location Method

JavaScript has two location methods: the indexOf () method and the lastIndexOf () method. Both methods receive two parameters: the item to be searched and (optional) the index of the starting position.

The indexOf () method indicates to search backward from the beginning of the array, and lastIndexOf () indicates to search forward from the end of the array. They all return the position of the item to be searched in the array. If no position is found,-1 is returned. When the first parameter is compared with each item in the array, the full parameter is used.

var nums = [1,2,3,4,5,6];alert(nums.indexOf(3)); // 2alert(nums.lastIndexOf(5)); // 4alert(nums.indexOf(3,1));  // 2alert(nums.lastIndexOf(4,4));  // 3

8. Iteration Method

JavaScript provides five Iteration Methods for arrays. Each method receives two parameters: the function to run on each item and (optional) The scope object for running the function-the value that affects this. Parameters to be passed in: the value of the array item, the position of the item in the array, and the array object itself.

• Every (): run the given function for each item in the array. If the number of rows returns true for each item, true is returned.

• Filter (): If you run a given function for each item in the array, an array consisting of true items is returned.

• ForeEach (): runs the given function for each item in the array without returning the value.

• Map (): a function that runs a given function for each item in the array and returns the result of each function call.

• Some (): run the given function for each item in the array. If any item returns true, the function returns true.

The preceding methods do not modify the values contained in the array.

9. Merge Method

JavaScript has two methods to merge Arrays: reduce () and reduceRight (). Both methods iterate all the items in the array and construct a final returned value. The reduce () method starts from the first entry of the array, and the reduceRight () method starts from the last entry of the array.

Both of them can receive two parameters: a function called on each item and (optional) are used as the initial values for merging. The functions passed to reduce () and reduceRight () receive four parameters: the index of the previous value, current value, and item, and the array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs in the second item of the array. Therefore, the first parameter is the first item of the array, and 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

When the callback function is executed for the first time, the prev value is 1 and the cur value is 2. The second time, prev is 3 (1 + 2) and cur is 3 (the value of the third item in the array), knowing that each item is accessed.

The role of reduceRight () is similar, but in the opposite direction.

The above JavaScript: the full analysis of the Array type is all the content shared by the editor. I hope to give you a reference and support for the script.

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.