Home > Web Front-end > JS Tutorial > body text

js array method

不言
Release: 2018-04-04 11:35:36
Original
1256 people have browsed it

The content of this article is the js array method. Now I share it with you, and you can also give it as a reference to friends in need


Array Creation

There are two ways to create an array in JavaScript. The first is to use Array Constructor:

##1

2

3

var arr1 = new Array(); //Create an empty array

var arr2 = new Array(20); // Create an array containing 20Array of items

var arr3 = new Array("lily","lucy", "Tom"); // Create an array containing 3 strings

The second basic way to create an array is to use array literal notation:

When reading and setting values ​​from an array, use square brackets and provide the 0 -based numeric index of the corresponding value:

1

2

##3

var arr4 = []; //Create an empty array

var arr5 = [20]; // Create a file containing 1Array of items

var arr6 = ["lily","lucy","Tom"]; // Create a containing3 array of strings

1

##2

3

4

var arr6 = ["lily" ,"lucy","Tom"]; // Create an array containing 3 strings

alert(arr6[0]); //lily

arr6[1] = "mary"; //Modify the second item to mary

arr6[3] = "sean"; //Add the fourth item to sean

##JavaScript

The length attribute of the array in can be modified, see the following example:

##1var

2

##3

arr = ["lily","lucy", "Tom"]; // Create an array containing 3 stringsarr[arr.length] =

"sean"

; // in subscript Add an item "sean"arr.length = arr to 3 (that is, the end of the array) .length-1;

//

Delete the last item of the array

If you need to determine whether an object is an array object, before ECMAScript 5, we can use instanceof Array To judge, but the problem with the instanceof operator is that it assumes that there is only one global execution environment. If the web page contains multiple frames, there are actually more than two different global execution environments, and thus more than two different versions of the Array constructor. If you pass an array from one frame to another, the array you pass in will have a different constructor than the array created natively in the second frame.

ECMAScript 5 Newly added Array.isArray() method. The purpose of this method is to ultimately determine whether a value is an array, regardless of the global execution context in which it was created.

Array method

#The following is an introduction to the array method. The array method includes the array prototype method, and also from object Methods inherited from objects. Here we only introduce the prototype methods of arrays. The main array prototype methods are as follows:

join()
push()
and pop()
shift()
and unshift()
sort()
reverse()
concat()
slice()
splice()
indexOf()
and lastIndexOf() ES5New)
forEach()
ES5Newly added)
map()
ES5Newly added)
filter( )
ES5New)
every()
ES5 Newly added)
some()
ES5Newly added)
reduce()
and reduceRight() (ES5new)

New method browser support for ES5:

Opera 11+
Firefox 3.6 +
Safari 5+
Chrome 8+
Internet Explorer 9+

For supported browser versions, you can pass ArrayPrototype extension to achieve. The basic functions of each method are introduced in detail below.

1join()

join(separator ): Combine the elements of the array into a string, using separator as the separator. If omitted, the default comma is used as the separator. This method only Receives one parameter: the delimiter.

##1

##2

3

4

##var arr = [1,2,3];

##console.log(arr.join());

// 1,2,3

console.log(arr.join(

"-")); // 1-2-3

console.log(arr);

// [1, 2, 3](The original array remains unchanged)

Duplicate strings can be realized through the

join() method, just pass in the string and the repeated times, the repeated string can be returned. The function is as follows:

2, push() and pop()

push(): 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.
pop()
: Remove the last item from the end of the array, reduce the length value of the array, and then return the removed item item.

1

2

3

4

5

function repeatString(str, n) {

return new Array(n + 1).join(str);

}

console. log(repeatString(

"abc", 3)); // abcabcabc

console.log(repeatString (

"Hi", 5)); // HiHiHiHiHi

##1

##2

3

4

5

6

7

##var

arr = ["Lily","lucy","Tom"];# #var

count = arr.push("Jack","Sean"); console.log(count);

// 5

console.log(arr);

// ["Lily", "lucy", "Tom", "Jack", "Sean"]

var

item = arr.pop();##console.log(item); // Sean

console .log(arr); // ["Lily", "lucy", "Tom", "Jack"]

3, shift() and unshift()

shift(): Delete the first item of the original array and return the value of the deleted element; if the array is empty, it returns undefined .
unshift:
Add parameters to the beginning of the original array and return the length of the array.

This set of methods is the same as the above push() and pop() methods Corresponding exactly, one is the beginning of the operation array, and the other is the end of the operation array.

##1

##2

3

4

5

6

7

##var

arr = ["Lily","lucy","Tom"];# #var

count = arr.unshift("Jack","Sean"); console.log(count);

// 5

console.log(arr);

//["Jack", "Sean", "Lily", "lucy", "Tom"]

var

item = arr.shift();##console.log(item); // Jack

console .log(arr); // ["Sean", "Lily", "lucy", "Tom"]

4sort()

sort() : Arrange the array items in ascending order ——That is, the smallest value is at the front and the largest value is at the back.

When sorting, the sort() method will call toString()## for each array item # Transformation method and then compares the resulting strings to determine how to sort. Even if each item in the array is a numeric value, the sort() method compares strings, so the following situation will occur:

1

##2

3

4

5

#var

arr1 = ["a", "d", "c" , "b"];##console.log(arr1.sort()); // [ "a", "b", "c", "d"]

##arr2 = [13, 24, 51, 3];console.log(arr2.sort());

// [13, 24, 3, 51]

##console.log(arr2);

// [13, 24, 3, 51](The metaarray is changed

)

In order to solve the above problem, the sort() method can receive a comparison function as a parameter so that we can specify which value is in front of which value. The comparison function accepts two parameters and returns a negative number if the first parameter should be before the second. If the two parameters are equal, it returns 0 if the first parameter should be After the second one, a positive number is returned. The following is a simple comparison function:

If you need to use the comparison function to produce descending sorted results, just exchange the values ​​returned by the comparison function:

1

2

3

4

5

6

7

8

9

10

11

function compare(value1, value2) {

if (value1 < value2) {

##return -1;

} else if (value1 > value2) {

return 1;

} else {

return 0;

}

}

arr2 = [13, 24, 51, 3];

console.log(arr2.sort(compare)); // [3, 13, 24, 51]

5

1

2

3

4

5

6

7

8

9

10

11

##function compare(value1, value2) {

##if (value1 < value2 ) {

return 1;

}

else if (value1 > value2) {

return -1;##}

else {# #return

0;}

}

arr2 = [13, 24, 51, 3];

##console.log(arr2.sort(compare)); // [51, 24, 13, 3]

reverse()reverse(): Reverse the order of array items.

##1##2

3

##var

arr = [13, 24, 51, 3];

console.log(arr.reverse()); //[3, 51, 24, 13]

console.log( arr);

//[3, 51, 24, 13](Original array changed

)

6concat()

concat() : Add parameters to the original array. This method will first create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly constructed array. Without passing arguments to the concat() method, it simply copies the current array and returns the copy.

From the above test results, we can find that if the input is not an array, then the parameters will be added directly to the back of the array. If the input is an array, the array will be added. Each item in is added to the array. But what if a two-dimensional array is passed in?

##1

##2

3

4

##var

arr = [1, 3,5,7];

var

arrCopy = arr.concat(9,[11,13]); console.log(arrCopy);

//[1, 3, 5, 7, 9, 11, 13]console.log(arr);

// [1, 3, 5, 7](The original array has not been modified)

##1

##2

3

##var

arrCopy2 = arr.concat([9,[11,13]]);

console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]

console.log(arrCopy2[5]); //[11, 13]

In the above code, the fifth item of the arrCopy2 array is an array containing two items, which means concatThe method can only add each item in the incoming array to the array. If some items in the incoming array are arrays, then this array item will also be added as one item to arrCopy2 middle.

7slice()

slice() : Returns a new array composed of items from the specified starting index to the ending index in the original array. slice()The method can accept one or two parameters, which are the starting and ending positions of the item to be returned. With only one argument, the slice() method returns all items starting at the position specified by the argument to the end of the current array. If given two arguments, this method returns items between the start and end positions - but not including the end position.

##1

##2

3

4

5

6

7

##8

9

10

var

arr = [1,3,5,7,9,11];##var

arrCopy = arr.slice(1);var

arrCopy2 = arr.slice(1,4);var

arrCopy3 = ​​arr.slice(1,-2);var

arrCopy4 = arr.slice(-4,-1);console.log( arr);

//[1, 3, 5, 7, 9, 11](

The original array has not changed)console.log(arrCopy);

//[3, 5, 7, 9, 11]

##console.log(arrCopy2); //[3, 5, 7]

console.log(arrCopy3); //[3, 5, 7]

console.log(arrCopy4); //[5, 7, 9]

arrCopy only sets one parameter, that is, the starting subscript is 1, so the returned array is the subscript 1 (including the subscript 1) starts from the end of the array.
arrCopy2
sets two parameters and returns the starting subscript (including 1) and the ending subscript (not A subarray including 4).
arrCopy3
Set two parameters, the termination subscript is a negative number, when a negative number appears, add the negative number to the value of the array length (6) to replace the number at that position, so it is the substring starting from 1 to 4 (exclusive) array.
arrCopy4
Both parameters are negative numbers, so add the array length 6 to convert them into positive numbers, so they are equivalent to slice(2,5).

8splice()

splice() : A very powerful array method. It has many uses and can achieve deletion, insertion and replacement.

Delete: You can delete any number of items, just specify 2 parameters: the position and number of the first item to be deleted The number of items deleted. For example, splice(0,2) will delete the first two items in the array.

Insert: You can insert any number of items into the specified position, just provide 3 parameters: starting position, 0 (the number of items to delete) and the items to insert. For example, splice(2,0,4,6) will insert ## starting from the current array position 2 #4 and 6.
Replacement: You can insert any number of items into the specified position and delete any number of items at the same time. Just specify 3 parameters: starting position, number of items to delete, and any number of items to insert. The number of items inserted does not have to equal the number of items deleted. For example, splice (2,1,4,6) will delete the item at current array position 2 , and then remove it from position 2 Begin by inserting 4 and 6.

splice()The method always returns an array containing the items removed from the original array, or an empty value if no items were removed. array.

#9
##1

##2

3

4

5

6

7

8

9

10

var arr = [1,3,5,7,9,11];

var arrRemoved = arr.splice(0,2);

##console.log(arr); //[5, 7, 9, 11]

console.log(arrRemoved); //[1, 3]

var arrRemoved2 = arr.splice(2,0,4,6);

##console.log(arr);

/ / [5, 7, 4, 6, 9, 11]##console.log(arrRemoved2);

// []

var

arrRemoved3 = arr.splice(1,1,2,4);console.log(arr );

// [5, 2, 4, 4, 6, 9, 11]##console.log(arrRemoved3);

//[7]

indexOf() and lastIndexOf()indexOf(): Receives two parameters: the item to be found and (Optional) An index indicating the starting location of the search. Among them,

searches backward from the beginning of the array (position 0). lastIndexOf: Receives two parameters: the item to be found and (optional) the index indicating the starting point of the search. Among them, searches forward starting from the end of the array.
Both methods return the position of the item to be found in the array, or -

1 if not found. . The equality operator is used when comparing the first argument to each item in the array.

##1##2arr = [1,3,5,7,7,5,3,1];

3

4

5

6

var

console.log(arr.indexOf(5)); //2

##console.log(arr.lastIndexOf(5));

//5

console.log(arr.indexOf(5,2));

//2

console.log(arr.lastIndexOf(5,4));

//2##console.log(arr.indexOf(

"5")); //-1

10forEach()

forEach() : Loop through the array and run the given function on each item in the array. This method has no return value. The parameters are all of the function type. By default, parameters are passed. The parameters are: the traversed array content; the corresponding array index, and the array itself.

#11

##1

##2

3

4

5

6

7

##8

9

10

var

arr = [1, 2, 3, 4, 5];arr .forEach(

function(x, index, a){console.log(x +

'|' + index + '|' + (a === arr)); });

//

The output is: // 1|0|true

// 2|1|true

// 3|2|true

// 4|3|true

// 5|4|true

, map()map()

: refers to

"Mapping", runs the given function on each item in the array, and returns an array composed of the results of each function call. The following code uses the

map

method to square each number in the array.

##1arr = [1, 2, 3, 4, 5];
##2

3

4

5

##var

var arr2 = arr .map(

function(item){return item*item;

});console.log(arr2);

//[1, 4, 9, 16, 25]

12filter()

filter() : "Filtering" Function, each item in the array runs the given function and returns an array that meets the filtering conditions.

13

##1

##2

3

4

5

##var

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];##var

arr2 = arr.filter(function(x, index) { return

index % 3 === 0 || x >= 8;});

console.log(arr2);

//[1, 4, 7, 8, 9, 10]

every()every()

: Determine whether each item in the array meets the conditions. Only if all items meet the conditions will

true be returned.

##1arr = [1, 2, 3, 4, 5];
##2

3

4

5

6

7

##8

9

var

var arr2 = arr.every(

function(x) {return x < 10;

});##console.log(arr2);

// true

var arr3 = arr.every(

function(x) {return x < 3;

##}); console.log(arr3); // false

14some()

some() : Determine whether there are items in the array that meet the conditions. As long as one item meets the conditions, true will be returned.

##1

##2

3

4

5

6

7

##8

9

var

arr = [1, 2, 3, 4, 5];

var

arr2 = arr.some(function(x) {

return

x < 3;});

##console.log(arr2);

// true

var

arr3 = arr.some(function(x) {return

x < 1;##});

console.log(arr3); // false

15, reduce() and reduceRight()

Both methods will iterate over all items of the array and then construct a final returned value. reduce()The method starts from the first item of the array and traverses to the end one by one. And reduceRight() starts from the last item of the array and traverses forward to the first item.

Both methods accept two parameters: a function to be called on each item and (optionally) an initial value to use as the basis for the merge.

Functions passed to reduce() and reduceRight() receive 4 parameters: previous value, current value, index of item and array object. Any value returned by this function is automatically passed to the next item as the first parameter. The first iteration occurs over the second item of the array, so the first argument is the first item of the array and the second argument is the second item of the array.

The following code uses reduce() to implement array summation. An initial value is added to the array at the beginning10 .

This article is reproduced from

##1

##2

3

4

5

##var

values ​​= [1,2,3,4,5];##var

sum = values .reduceRight(function(prev, cur, index, array){return

prev + cur;},10);

console.log(sum);

//25

http://www.jb51. net/article/87930.htm Related recommendations:

JS array sorting

js function encapsulation


The above is the detailed content of js array method. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!