js array method

不言
Release: 2018-04-04 11:35:36
Original
1184 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 useArrayConstructor:

##1

2

3

vararr1 =newArray();//Create an empty array

vararr2 =newArray(20);//Create an array containing20Array of items

vararr3 =newArray("lily","lucy","Tom");//Create an array containing3strings

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 the0-based numeric index of the corresponding value:

1

2

##3

vararr4 = [];//Create an empty array

vararr5 = [20];//Create a file containing1Array of items

vararr6 = ["lily","lucy","Tom"];//Create a containing3array of strings

1

##2

3

4

vararr6 = ["lily","lucy","Tom"];//Create an array containing3strings

alert(arr6[0]);//lily

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

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

##JavaScript

Thelengthattribute of the array incan be modified, see the following example:

##1 var

2

##3

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

"sean"

;//in subscript Add an item"sean"arr.length = arr to3(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, beforeECMAScript 5, we can useinstanceof ArrayTo judge, but the problem with theinstanceofoperator 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 theArrayconstructor. 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 5Newly addedArray.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 fromobjectMethods inherited from objects. Here we only introduce the prototype methods of arrays. The main array prototype methods are as follows:

join()
push()
andpop()
shift()
andunshift()
sort()
reverse()
concat()
slice()
splice()
indexOf()
andlastIndexOf()ES5New)
forEach()
ES5Newly added)
map()
ES5Newly added)
filter( )
ES5New)
every()
ES5Newly added)
some()
ES5Newly added)
reduce()
andreduceRight()(ES5new)

New method browser support forES5:

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

For supported browser versions, you can passArrayPrototype 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, usingseparatoras the separator. If omitted, the default comma is used as the separator. This method only Receives one parameter: the delimiter.

##1

##2

3

4

##vararr = [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()andpop()

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 thelengthvalue of the array, and then return the removed item item.

1

2

3

4

5

functionrepeatString(str, n) {

returnnewArray(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()andunshift()

shift(): Delete the first item of the original array and return the value of the deleted element; if the array is empty, it returnsundefined.
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 abovepush()andpop()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, thesort()method will calltoString()## 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, thesort()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 returns0if 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

functioncompare(value1, value2) {

if(value1 < value2) {

##return-1;

}elseif(value1 > value2) {

return1;

}else{

return0;

}

}

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

##functioncompare(value1, value2) {

##if(value1 < value2 ) {

return1;

}

elseif(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 theconcat()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 thearrCopy2array is an array containing two items, which meansconcatThe 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 toarrCopy2middle.

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, theslice()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]

arrCopyonly sets one parameter, that is, the starting subscript is1, so the returned array is the subscript1(including the subscript1) starts from the end of the array.
arrCopy2
sets two parameters and returns the starting subscript (including1) and the ending subscript (not A subarray including4).
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 from1to4(exclusive) array.
arrCopy4
Both parameters are negative numbers, so add the array length6to convert them into positive numbers, so they are equivalent toslice(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 specify2parameters: 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 provide3parameters: 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 position2#4and6.
Replacement: You can insert any number of items into the specified position and delete any number of items at the same time. Just specify3parameters: 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 position2, and then remove it from position2Begin by inserting4and6.

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

vararr = [1,3,5,7,9,11];

vararrRemoved = arr.splice(0,2);

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

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

vararrRemoved2 = 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()andlastIndexOf()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 (position0).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 ##2 arr = [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 thefunctiontype. 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.

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

3

4

5

##var

vararr2 = arr .map(

function(item){returnitem*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

truebe returned.

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

3

4

5

6

7

##8

9

var

vararr2 = arr.every(

function(x) {returnx < 10;

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

// true

vararr3 = arr.every(

function(x) {returnx < 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,truewill 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()andreduceRight()

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. AndreduceRight()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 toreduce()andreduceRight()receive4parameters: 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 usesreduce()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.htmRelated 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
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!