Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript array (Array)_Basic knowledge

Detailed explanation of JavaScript array (Array)_Basic knowledge

WBOY
Release: 2016-05-16 16:06:29
Original
1253 people have browsed it

ECMAScript arrays are quite different from arrays in other languages. Although arrays in ECMAScript are also ordered lists, each item in the array can hold any type of data. The size of ECMAScript arrays can be dynamically adjusted.
There are two basic ways to create an array. The first is to use the Array constructor, as shown below:

Copy code The code is as follows:

var colors = new Array();

If you know the number of items to be saved in the array, you can also pass a parameter to the constructor, and the parameter will automatically become the value of the length attribute, as follows:
Copy code The code is as follows:

var colors = new Array(20);

You can also pass the items that should be included in the array to the Array constructor, as shown in the following code:
Copy code The code is as follows:

var colors = new Array("red","blue");

In addition, you can also omit the new operator when using the Array constructor, as shown below:
Copy code The code is as follows:

var colors = Array(20);

The second way to create an array is to use array literal notation. An array literal is represented by a pair of square brackets containing the array items, separated by commas, as follows:
Copy code The code is as follows:

var color = ["red","blue"];
var names = [];
var values ​​= [1,2,]//IE8 and the previous 3 items, the other 2 items are not recommended to be used

Like objects, Array's constructor will not be called when using numeric literal representation.
When reading and setting the values ​​of an array, use square brackets and provide the 0-based numeric index of the corresponding value, as follows:
Copy code The code is as follows:

var colors = ["red","blue"]; //Define array
alert(colors[0]); //red
colors[1] = "black" //Modify item 2
colors[2] = "brown" //Add 3rd

The number of items in an array is stored in its length property, which always returns 0 or a greater number, as shown below:
Copy code The code is as follows:

var colors = ["red","blue"]; //Define array
var names=[];
alert(colors.length); //3
alert(names.length) //0

It is worth noting that the length value of the array is not read-only. So, by setting this value, you can move items from the end of the array or add items to the array, like this:
Copy code The code is as follows:

var colors = ["red","blue"];
colors.length = 1;
alert(colors[1]); //undefined

You can also use the length attribute to easily add data to the end of the array:
Copy code The code is as follows:

var colors = ["red","blue"];
colors[colors.length] = "black"; //Add
at position 2 colors[colors.length] = "brown"; //Add
at position 3

1. Detection array

For a web page or a global scope, you can use the instanceof operator:

Copy code The code is as follows:

if(value instanceof Array){
//Perform operation
}

The limitation of the instanceof operator is the global scope. If the web page contains multiple frames, there will be more than two global execution environments. In order to solve this problem, ECMAScript5 added the Array.isArray() method, which is used as follows:
Copy code The code is as follows:

if(Array.isArray(value)){
//Perform operation
}

2. Conversion method
Calling the toString() method of an array will return a comma-separated string concatenated from the string form of each value in the array. And calling valueOf() still returns an array. As shown below:

Copy code The code is as follows:

var colors = ['red', 'blue', 'green'];
alert(colors.toString()); //red,blue,green
alert(colors.valueOf()); //red,blue,green
alert(colors) //red,blue,green

The toLocalString(), tiString(), and valueOf() methods inherited by arrays all return array items in the form of comma-separated strings by default. And if you use the join() method, you can use different delimiters to build this string. The join() method only accepts one parameter, which is the string used as the separator, as shown below:
Copy code The code is as follows:

var colors = ['red', 'blue', 'green'];
alert(colors.join(',')); //red,blue,green
alert(colors.join('|')); //red|blue|green

If the value of an item in the array is null or undefied, the value will be represented by an empty string in the return results of the join(), toLocalString(), tiString() and valueOf() methods.

3. Stack method

Javascript provides push() and pop() operations specifically for arrays to achieve stack-like behavior.

The push() method can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array. The pop() method overflows the last item from the end of the array, decrements the length of the array, and returns the removed item.

Copy code The code is as follows:

var colors = new Array(); //Define array
var count = colors.push("red", "blue"); //Push two items
alert(count); //2
count = colors.push("black"); //Push another item
alert(count); //3
var item = colors.pop(); //Pop the last item
alert(item); //"black"
alert(colors.length); //2

4. Queue method

The access rule of the stack data structure is LIFO (last in first out), while the access rule of the queue is FIFO (first in first out). The queue adds items at the end of the list and removes items at the front.

The shift() method removes the first item in the array and returns the item, the length-1 of the array. Combining the push() and shift() methods, arrays can be used like queues, as shown below:

Copy code The code is as follows:

var colors = new Array();
var count = colors.push("red", "blue");
count = colors.push("black");
alert(count);
var item = colors.shift(); //Get the first item
alert(item); //"red"
alert(color.length); //2

ECMAScript also provides the unshift() method for arrays. The unshift() and shift() methods do the opposite: they add an arbitrary number of items to the front of the array and return the length of the new array. Therefore, using the unshift() and shift() methods together, you can simulate a queue in the opposite direction, adding new items at the front of the array and removing items from the end of the array, as follows:

Copy code The code is as follows:

var colors = new Array();
var count = colors.push("red", "green");
alert(count); //2
count = colors.unshift("black"); //Push another item
alert(count); //3
var item = colors.pop(); //Get the last item
alert(item) //green
alert(colors.length) //2

5. Reordering method
There are already two methods in the array that can be used directly to reorder: reverse() and sort(). The reverse() method will reverse the order of the array items.

Copy code The code is as follows:

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

By default, the sort() method arranges the array items in ascending order, calling the toString() method of each item and comparing the strings to determine how to sort. Even if each item in the array is a numeric value, the sort() method compares strings.
Copy code The code is as follows:

var values ​​= [12, 11, 3, 4, 5];
values.sort();
alert(values); //12,11,3,4,5

We can pass a comparison function as a parameter to the sort() method. As follows:
Copy code The code is as follows:

function compare(value1, value2) {
If (value1 < value2) {
Return -1
} else if (value1 > value2) {
         return 1
} else {
         return 0
}
}
var values ​​= [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //0,1,5,10,15

6. Operation method
ECMAScript provides many methods for operating on arrays. Among them, the concat() method can create a new array based on all items in the current array.

Copy code The code is as follows:

var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors); //red,green,blue
alert(colors2); //red,green,blue,yellow,black,brown

The slice() method can create a new array based on one or more items of the current array. It can receive one or two parameters, which are the starting and ending positions of the items to be returned. If one argument is given, returns all items from the position specified by the argument to the end of the current array. Two parameters return all items starting at the specified position - excluding items at the end position. Note that the slip() method does not affect the original array.
Copy code The code is as follows:

var colors=["red","green","blue","black","brown"];
var colors2=colors.slice(1);
var colors3=colors.slice(1,4);
alert(colors2); //green,blue,black,brown
alert(colors3); //green,blue,black

Slice() method deletion: You can delete any number of items, just specify 2 parameters: the position of the first item to be deleted and the number of items to be deleted.
Slice() method insertion: You can insert any number of items into the specified position by providing only 3 parameters: starting position, 0 (number of items to be deleted) and items to be inserted.
Replacement of slipe() method: You can insert any number of items at the specified position and delete any number of items at the same time. You only need to specify 3 parameters: starting position, number of items to be deleted, and any number of items to be inserted.
Copy code The code is as follows:

var colors = ["red", "green", "blue"];
//Delete
var removed = colors.slice(0, 1); //Remove item 1
var colors3 = colors.slice(1, 4);
alert(colors); //green,blue
alert(removed); //red
//Insert
removed = colors.slice(1, 0, "yellow", "orange"); //Insert
starting from position 1 alert(colors); //green,yellow,orange,blue
alert(removed); //Empty array
//Replace
removed = colors.slice(1, 1,"red","purple"); //Insert
starting from position 1 alert(colors); //green,"red","purple",orange,blue
alert(removed); //"yellow"

7. Position method
ECMAScript5 provides two position methods for arrays: indexOf() and lastIndexOf(). Both methods receive two parameters: the item to be found and an optional index indicating where to start the search. The indexOf() method searches sequentially from the beginning of the array, and the lastIndexOf() method searches forward from the end of the array.
Both methods return the position of the item to be found in the array, and return -1 if not found.

Copy code The code is as follows:

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

8. Iteration method

ECMAScript5 defines 5 iteration methods for arrays. Each method accepts two parameters, the first is the function to be iterated, and the second is the scope object of the function [optional].

The iteration function accepts three parameters. The first is the value of the element in the array to be iterated, the second is the position of the element in the array to be iterated, and the third is the iterated array itself.

1. every() runs the given function on each item in the array. If the function returns true for each item, it returns true
2. filter() runs the given function on each item in the array and returns an array of items for which the function returns true.     
3. forEach() runs the given function on each item in the array. This method has no return value. 4. map() runs the given function on each item in the array and returns the result of each function call. Array
5. some() runs the given function on each item in the array. If the function returns true for any item, it returns true
The browsers supported by these iteration methods are IE9, Firefox2, Safari3, Opera 9.5, chrome
Among these methods, the most similar ones are every() and some(), both of which are used to query whether the items in the array meet a certain condition. For every(), the function passed in must return true for each item before this method returns true; otherwise, it returns false. The some() method returns true as long as the function passed in returns true for a certain item in the array.

Copy code The code is as follows:

var num = [1,2,3,4,5,6,7,8,9];
var everyResult = num.every(function(item, index, array) {
If(item > 2) {
        return true;
}
});
alert(everyResult); //false
var someResult = num.some(function(item) {
If(item > 2) {
        return true;
}
});
alert(someResult); //true

Filter() uses a specified function to determine whether a certain item is included in the returned array.

Copy code The code is as follows:

var num = [1,2,3,4,5,4,3,2,1];
var filterResult = num.filter(function(item) {
If(item > 2) {
        return true;
}
});
alert(filterResult); //[3,4,5,4,3]

map() also returns an array, and each item in this array is the result of running the passed function on the corresponding item in the original array.

Copy code The code is as follows:

var num = [1,2,3,4,5,4,3,2,1];
var mapResult = num.map(function(item) {
If(item > 2) {
        return true;
}
}); //[2,3,6,8,10,8,6,4,2]

forEach() runs the passed function on each item in the array. This method has no return value and is essentially the same as using a for loop to iterate over an array.

Copy code The code is as follows:

var num = [1,2,3,4,5,4,3,2,1];
num.forEach(function(item) {
//Perform operation
});

9. Merge method

Two new methods have been added to ECMAScript5: reduceRight() and reduce(). Both methods accept two parameters: the first is a function used to iterate the array. This function has four parameters: the previous value, the current value, the index of the item, and the array object. However, any value of this function will be automatically passed to the next item as the first parameter. The second one is used as the initial value of the first parameter in the first function.

Copy code The code is as follows:

var nums = [1,2,3,4,5];
var sum = nums.reduce(function(prev, cur, index, array) {
Return prev cur;
});
alert(sum);//15
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template