JavascriptArray array common method _ javascript skills

Source: Internet
Author: User
This article mainly introduces the common methods of javascriptArray arrays. For more information, see (1) Basic Array Method

1. join ()

The Array. join () method converts all elements in the Array into strings and concatenates them to return the final string generated. You can specify the Separator by yourself. If not specified, commas are used by default.

Var arr = [1, 2, 3]; console. log (arr. join (); // "1, 2, 3" console. log (arr. join ("-"); // "1-2-3" var a = new Array (10); // an empty Array with a length of 10 to form the following string console. log (. join ("-"));//"---------"

2. reverse ()
The Array. reverse () method reverses the elements in the Array and returns the reverse Array (the returned Array is itself, and the original Array has changed)

var arr = [1,2,3];arr.reverse();console.log(arr.join());//"3,2,1"

Therefore, if you want to reverse a string, you can

Var str = "abcdefg"; console. log (str. split (""). reverse (). join (""); // "gfedcba" returns the new value console. log (str); // "abcdefg" of course, the original is not changed.

3. sort ()
The Array. sort () method sorts the elements in the Array and returns the sorted Array.

When parameters are not included, they are sorted sequentially by default, that is, from small to large. Of course, you can also directly add a comparison function to sort.

Var arr = [1, 4, 7]; arr. sort (); console. log (arr); // [1, 4, 7] arr. sort (function (a, B) {return a-B; // from small to large}); console. log (arr); // [1, 4, 7] arr. sort (function (a, B) {return B-a; // from large to small}); console. log (arr); // [7, 4, 1] var num = new Array ('one', 'three ', 'six', 'five'); num. sort (); // case sensitive sorting console. log (num); // ["Five", "Six", "one", "three"] num. sort (function (s, t) {var a = s. toLowerCase (); var B = t. toLowerCase (); if (
 
  
B) return 1; return 0;}); console. log (num); // ["Five", "one", "Six", "three"]
 

4. concat ()
The Array. concat () method is created and a new Array is returned. Its elements include the elements of the original Array that calls concat () and each parameter of concat.

If any of these parameters is an array, the elements of the array are connected instead of the array.

Note that concat () does not recursively flatten the array. Concat () does not modify the called array.

var arr = [1,2,3];console.log(arr.concat(4,5)); // [1, 2, 3, 4, 5]console.log(arr);       // [1, 2, 3]console.log(arr.concat([4,5])); // [1, 2, 3, 4, 5]console.log(arr.concat([4,5],[6,7])); // [1, 2, 3, 4, 5,6,7]console.log(arr.concat([4,[5,[6,7]]])); // [1, 2, 3, 4, [5, [6, 7]]]console.log(arr.concat(4,[5,[6,7]])); // [1, 2, 3, 4, 5,[6,7]]

5. slice ()
The Array. slice () method returns a fragment or sub-Array of the specified Array. Its Two Parameters specify the start and end positions (a, B) of the fragment respectively ). The returned result is an array element that does not contain B from a to B.
If there is only one parameter (a), it indicates the elements from a to the end of the array.
If a negative value (-a) exists in the parameter, it indicates the position a relative to the last element in the array. For example, (-3) indicates the last and third elements to the end. If a negative number is displayed, it is first converted and then determined according to the range rules.
It also returns a new array without modifying the original array.

var arr = [1,2,3,4,5];console.log(arr.slice(0,3)); // [1, 2, 3]console.log(arr); // [1, 2, 3, 4, 5]console.log(arr.slice(3));//[4, 5]console.log(arr.slice(-3));// [3, 4, 5]console.log(arr.slice(-3,-1));// [3, 4]console.log(arr.slice(2,-1));// [3, 4]

6. splice ()
The Array. splice () method is a common method for inserting or deleting elements in an Array. It modifies the value of the original array and returns a new array sequence.

The first parameter of splice () specifies the start position of insertion or deletion, and the second parameter specifies the number of elements to be deleted from the array. If the second parameter is omitted, It is deleted to the end by default.

var arr = [1,2,3,4,5,6,7,8];console.log(arr.splice(4)); //[5, 6, 7, 8]console.log(arr); // [1, 2, 3, 4]console.log(arr.splice(1,2));// [2, 3]console.log(arr); // [1, 4]

The first two parameters of splice () Specify the array elements to be deleted. Any number of parameters followed by this parameter specifies the elements to be inserted into the array, and the insertion starts from the position represented by the first parameter.

Unlike the concat () above, splice () directly inserts an array, for example, the following [1, 2]

var arr = [1,2,3,4,5];console.log(arr.splice(2,0,'a','b')); // []console.log(arr); // [1, 2, "a", "b", 3, 4, 5]console.log(arr.splice(2,1,[1,2],3));// ["a"]console.log(arr); // [1, 2, [1, 2], 3, "b", 3, 4, 5]

7. push () pop () unshift () shift ()
Think of these methods as stack operations: the first two are normal Stack operations, and the latter two are reverse stack operations.
Push () and unshift () add elements from the back and front of the array, and return the length of the new array.
Pop () and shift () Delete the last and foremost elements in the array, and return the deleted elements.

var arr = [];console.log(arr.push(1,2,3));//3console.log(arr);//[1, 2, 3]console.log(arr.pop());// 3console.log(arr);//[1,2]console.log(arr.push([4,5]));//3console.log(arr);// [1, 2, [4, 5]]

var arr = [];console.log(arr.unshift(1,2,3));//3console.log(arr);//[1, 2, 3]console.log(arr.shift());// 1console.log(arr);// [2, 3]console.log(arr.unshift([4,5]));//3console.log(arr);//[[4, 5], 2, 3]

(2) array method in ECMAScript5

Most of these array methods have uniform and general rules. They do not modify the original array.
The first parameter of most methods receives a function and calls this function once for each element (or element) of the array.

If it is a sparse array, the transmitted function is not called for nonexistent elements;
In most cases, the called function generally uses three parameters: array elements, element indexes, and arrays themselves. Generally, the last two parameters are not required.
In addition to the first parameter (function), there is a second parameter (Optional). If the second parameter exists, the called function is considered as the method of the second parameter.
That is to say, the second parameter passed in when a function is called is used as the value of its this keyword.

1. forEach ()

This method traverses the array from the beginning to the end and calls the specified function for each array.

Var data = [1, 2, 3, 4, 5]; var sum = 0; data. forEach (function (value) {// only the first parameter (function) is used, and the called function only uses the first parameter array element sum + = value ;}); console. log (sum); // 15console. log (data); // [1, 2, 3, 4, 5]

Var data = [1, 2, 3, 4, 5]; var sum = 0; data. forEach (function (value, item, data) {// The called function has three parameters: data [item] = value * value; // take the square}); console. log (data); // [1, 4, 9, 16, 25]

2. map ()
This method passes each element in the called array to the specified function and returns an array containing the return value of this function.

var data = [1,2,3,4,5];var data1 = data.map(function(value){ return ++ value;});console.log(data); // [1, 2, 3, 4, 5]console.log(data1);// [2, 3, 4, 5, 6]

3. filter ()
The array element returned by this method is a subset of the called array. The passed function is used for logic determination. This function returns true or false.

If the returned value is true or can be converted to true, the element passed to the judgment function is a member of this subset and will be added to an array as the return value.

var data = [1,2,3,4,5];var data1 = data.filter(function(value){ return value <= 3;});var data2 = data.filter(function(value){ return value > 3;});console.log(data); // [1, 2, 3, 4, 5]console.log(data1);// [1,2,3]console.log(data2);// [4,5]

4. every () and some ()
As the name implies, every () is returned when all elements in the array meet the conditions specified by the function. some () is returned when a certain element is satisfied.

var data = [1,2,3,4,5];var data1 = data.every(function(value){ return value < 4;});var data2 = data.some(function(value){ return value >4;});console.log(data); // [1, 2, 3, 4, 5]console.log(data1);// falseconsole.log(data2);// true

5. reduce () and reduceRight ()
These two methods use the specified function to combine array elements to generate a single value.

Reduce () has two parameters. The first is the function that executes the simplification operation. That is to say, two values are reduced to one in some way and the simplified values are returned.

The second parameter is optional and is passed to the first parameter function as the initial value. If the second parameter does not exist, the initial value uses the first element value of the array.

Var data = [1, 2, 3, 4, 5]; var sum = data. reduce (function (a, B) {return a + B;}); var sum1 = data. reduce (function (a, B) {return a + B ;}, 5); var min = data. reduce (function (a, B) {return (
 
  

Sum does not have the second parameter, so the initial value is the first array element. Step 1 + 2 = 3, step 2 3 + 3 = 6... get 15
There is a second parameter in sum1, so the initial value is 5, step 5 + 1 = 6, step 6 + 2 = 8... finally get 20

ReduceRight () is similar to reduce (). The difference is that it processes arrays from high to low (from right to left) according to the array index, rather than from normal to high.

Var data = ['A', 'B', 'C']; var str = data. reduce (function (x, y) {// return x + y;}); var str1 = data. reduceRight (function (x, y) {// return x + y;}); console. log (data); // [1, 2, 3] console. log (str); // "abc" console. log (str1); // "CBA"

6. indexOf () and lastIndexOf ()
This method is used to search for elements with a given value in the entire array, and returns the index of the element (if one value is found, it exits). If no value is found,-1 is returned.

One starts from beginning to end and one starts from end to end

Var data = ['A', 'B', 'A', 'C', 'a']; console. log (data. indexOf ('A'); // 0console. log (data. indexOf ('D'); //-1console. log (data. lastIndexOf ('A'); // 4console. log (data. lastIndexOf ('A',-2); // 2 starts from the second to the last. log (data. lastIndexOf ('A', 1); // 0 from the second forward of the order

7. array type isArray ()
Determines whether an object is an array.

Console. log (Array. isArray ([]); // trueconsole. log (Array. isArray ({}); // false // simulate the above var isArray1 = Function. isArray | function (o) {return typeof o = "object" & Object. prototype. toString. call (o) = "[object Array]" ;}; console. log (isArray1 ([]); // trueconsole. log (isArray1 ({})); // false
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.