Array types in JavaScript are very different from those in other languages. Each item in JavaScript can hold any type of data. Moreover, the size of JavaScript arrays can be adjusted dynamically and can automatically grow as data is added to accommodate new data .
There are two basic forms of creating an array.
1.Array constructor
var cities = new Array();
If you know the number of items to be saved in advance, you can also pass this number to the constructor, which will automatically become the value of the length attribute.
var cities = new Array(3);
You can also pass the items that should be included in the array to the Array constructor.
var cities = new Array("shanghai", "beijing", "shenzhen");The new operator can be omitted when creating an array:
var cities = Array(3); //Create an array containing 3 elements
2. Array literal representation
The array literal notation is represented by a pair of square brackets containing array items, separated by commas, as follows:
var cities = ["shanghai", "beijing", "shenzhen"];var cities = []; // Create an empty string
When reading and setting the value of an array, use square brackets and provide a numeric index based on 0 (based on 0 is counting from 0, the first term is 0, the second term is 1, and so on), as shown below:
var cities = ["shanghai", "beijing", "shenzhen"];alert(cities[0]); // "shanghai"cities[1] = "hongkong"; // Modify the second item "beijing" to "hongkong"cities[3] = "taiwan" // Add a new item
The number of items in the array is saved in the length property, and it is not read-only . Therefore, by setting the length property, you can remove items from the end of the array or add new items to the array.
var cities = ["shanghai", "beijing", "shenzhen"];cities.length = 2;alert(cities[2]); // undefined
Using this property of length, you can add new items at the end of the array:
var cities = ["shanghai", "beijing", "shenzhen"];cities[cities.length] = "hongkong";
1. Detect array
ECMAScript5 has added the Array.isArray() method, which is 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 toString() to return a comma-separated string spliced from the string form of each value in the array. For example:
var cities = ["shanghai", "beijing", "shenzhen"];alert(cities.toString()); // shanghai,beijing,shenzhenert(cities.valueOf()); // shanghai,beijing,shenzhenert(cities); // shanghai,beijing,shenzhenert(cities); // shanghai,beijing,shenzhen
Note: Since alert() needs to receive string parameters, it will call the toString() method in the background, so it will get the same result of calling the toString() method directly.
In addition, the toLocaleString() method often returns the same value as toString() and valueOf(). The difference is that in order to obtain the value of each item, the toLocaleString() method of each item is called , rather than 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 lines, and the toLocaleString method is called in the third line.
The toLocaleString(), toString() and valueOf() methods inherited by the array will return the array items in the form of comma-separated strings by default. With the join() method, you can use different characters to split the string and then return the string containing all array items.
var cities = ["shanghai", "beijing", "shenzhen"];alert(cities); // shanghai,beijing,shenzhenert(cities.join(","));// shanghai,beijing,shenzhenert(cities.join("|"));// shanghai|beijing|shenzhen3. Stack method
A stack is a last-in-first-out (LIFO) data structure, and the insertion and removal of data items in the stack can only occur at the top of the stack. JavaScript arrays provide push() and pop() methods for implementing stack-like behavior.
push() method
You can take 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); // 2From the above example, we can see that the number of inserted terms returned by the push() method.
pop() method
Remove the last item from the end of the array, reduce the length of the array, and return the removed item.
var params = new Array();var count = params.push("a", "b", "c");var item = params.pop();alert(item); // calendart(params.length); // 24. Queue method
The access rule for the data structure of the queue is first-in-first-out (FIFO), that is, the items are added from the end of the queue and the items are removed from the front end of the queue.
shift() method
The shift() method is provided in JavaScript, which removes the first item in the array and returns the item, and at the same time modifies the length attribute of the array.
var params = new Array();var count = params.push("a", "b", "c"); var item = params.shift(); // Get the first item alert(item); // aalert(params.length); // 2unshift() method
JavaScript also provides the unshift() method, which can add any item to 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,aIt was observed that if there are multiple terms in unshift() at a time, it will insert these terms into the array in order, that is, the first parameter is inserted into the front. As in the example above, "a" is inserted for the first time, "b" is inserted for the second time, and there are multiple terms when the third time, but the order is c in front and d in the back.
5. Reorder method
There are two methods directly used for reordering in the array.
reverse() method
The reverse() method inverts 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 resulting 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 this sorting is basically meaningless, and what we need is to sort the numerical values. The sort() method can receive a comparison function as an argument to specify the sorting rules.
The comparison function receives two parameters, returns a negative number if the first parameter should be before the second parameter, returns 0 if the two parameters are equal, and returns a positive number if the first parameter is after the second parameter.
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,536. Operation method
concat() method
A new array can be created based on all items in the current array. This method creates a copy of the current array, adds the parameters to the end of the copy, and returns the newly built 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,fslice() method
Creates a new array based on one or more items in the current array. The slice() method can receive one or two parameters, i.e. the start and end positions of the item to be returned . When there is only one parameter, it returns all items from the start item to the end of the array. When there are two parameters, it returns the item between the start position and the end position (excluding the end item). The slice() method will 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, and there are 3 ways to use it:
• Delete can delete any number of items, specify 2 parameters: the first item to be deleted and the number of items to be deleted, such as: splice(1,3) will delete the 2nd, 3rd, and 4th items in the array
var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];cities.splice(1,3);alert(cities); // beijing
• Insert You can insert any number of items into the specified position. Specify 3 parameters: starting position, 0 (number of items to be deleted), and item to be inserted
var cities = ["beijing", "shanghai", "shenzhen", "guangzhou"];cities.splice(1,0,"hongkong");alert(cities); // beijing,hongkong,shanghai,shenzhen,guangzhou
• Replace items that can replace the specified position. Specify 3 parameters: starting 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. Position method
There are two positional methods in JavaScript: indexOf() method and lastIndexOf() method. Both methods receive two parameters: the item to be found and (optional) index indicating the location of the search starting point.
The indexOf() method means looking backward from the beginning of the array, while the lastIndexOf() starts from the end of the array. They all return the position of the item found in the array, and -1 if not found. Congruent is used when comparing the first parameter with each item in the array.
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 5 iterative methods for arrays. Each method receives two parameters: the function to be run on each item and (optional) the scope object that runs the function - affecting the value of this. Parameters that need to be passed in: the value of the array item, the position of the item in the array, and the array object itself.
•every(): Runs a given function on each item in the array, and if the number of rows returns true for each item, it returns true.
•filter(): Run a given function on each item in the array, and return an array composed of items that will return true.
•forEach(): Runs a given function on each item in the array without returning a value
•map(): A function consisting of running a given function on each item in the array, returning the result of each function call.
•some(): Runs a given function on each item in the array. If any item returns true, the function returns true.
None of the above methods will modify the values contained in the array.
9. Merge method
There are two methods for merging arrays in JavaScript: reduce() and reduceRight(). Both methods iterate over all items of the array and then build a final returned value. Where, the reduce() method starts from the first item of the array, and reduceRight() starts from the last item of the array.
They can both receive two parameters: a function called on each item and (optional) as the initial value of the merge base. The function passed to reduce() and reduceRight() receives 4 parameters: the previous value, the current value, the index of the 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 on the second term of the array, so the first parameter is the first term of the array, and the second parameter is the second term of the array.
var values = [1,2,3,4,5];var sum = values.reduce(function(prev, cur, index, array){ return prev+cur;});alert(sum); // 15The first time the callback function is executed, prev is 1 and cur is 2. The second time, prev is 3(1+2), cur is 3(value of the third term of the array), knowing that each item is accessed.
reduceRight() has similar functions, but the direction is opposite.
The above comprehensive analysis of JavaScript:Array type is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.