ES6 common array Operations and tips summary

Source: Internet
Author: User
Tags function definition object object

Common methods 1. array.concat(array1, array2,...arrayN);

Merges multiple arrays, returns the new merged array, and does not change the original array.

Const ARRAY = [1,2].concat ([' A ', ' B '], [' name ']); // [1, 2, "a", "B", "name"]
2. array.every(callback[, thisArg]);

Detects whether each element in the array has passed the callback test, all by returning true, otherwise false is returned.

// the callback is defined as follows: element: The current value of the elements; index: current element subscript; array: current array function callback (element, index, array) {  ///  callback function must return TRUE or false to tell every whether to pass the test  return true false ;}
3. array.filter(callback[, thisArg]);

Returns a new array that contains all the elements tested by the callback function.

// the callback is defined as follows, three parameters: element: The current value of the elements; index: current element subscript; array: current array function callback (element, index, array) The  {///  callback function must return TRUE or FALSE, which returns true to preserve the element, false is not preserved.   returntruefalse= [1, 2, 3].filter (element = = element > 1 ); // filtered: [2, 3];
4. array.find(callback[, thisArg]);

Returns the first element tested through the callback function, otherwise the Undefined,callback function definition is returned as above.

Const FINDED = [1, 2, 3].find (element = = element > 1); // Finded:2

If you need to find the location of an element or if an element exists in the array, use ARRAY.PROTOTYPE.INDEXOF () or Array.prototype.includes ().

5. array.findIndex(callback[, thisArg]);

Returns the index of the first element tested by the callback function, otherwise the -1,callback function definition is returned as above.

Const FINDINDEX = [1, 2, 3].findindex (element = = element > 1); // findindex:1
6. array.includes(searchElement, fromIndex);

The includes () method is used to determine whether an array contains a specified value, which returns TRUE or false. Searchelement: the element to find; FromIndex: The index position at which to start the lookup.

[1, 2, 3].includes (2, 2); // false
7. array.indexOf(searchElement[, fromIndex = 0]);

Returns the first index in the array where a given element can be found, or 1 if it does not exist. Searchelement: the element to find; FromIndex: The index position at which to start the lookup.

[2, 9, 7, 8, 9].indexof (9); // 1

array.lastIndexOf(searchElement[, fromIndex = arr.length - 1])

Returns the last index of the specified element in the array, or 1 if it does not exist, looking forward from behind the array.

8. array.join(separator=‘,‘);

The elements in the array are concatenated into a string by separator, and the string is returned, separator defaults to ",".

[1, 2, 3].join ('; ') ); // "1;2;3"
9. array.map(callback[, thisArg]);

Returns a new array in which each element in the new array is returned as a result of calling the callback function. Note: If there is no return value, the new array will insert a undefined value.

Array.map because there is no filtering function, so when array calls the MAP function, if the data in the array is not each return, you must first filter and then map, that is, map calls must be valid for each element in the array.

Const MAPED = [{name: ' AA ', age:18}, {name: ' BB ', age:20}].map (item = item.name + ' c '); // maped: [' AAC ', ' BBC '];
10. array.pop() 与 array.shift();

Pop removes the last element from the array and returns the value of the last element, the last of the original array is deleted. Returns undefined when the array is empty.

[1, 2, 3].pop (); // 3

Shift deletes the first element of the array and returns the first element, and the first element of the original array is deleted. The array is empty to return undefined.

Const shifted = [' one ', ' one ', ' one ', ' three '].shift (); // shifted: ' One '
11. array.push(element1, element2, ....elementN) 与 array.unshift(element1, element2, ...elementN);

Push is to add one or more elements to the end of the array and return the length of the new array; Unshift adds one or more elements to the beginning of the array and returns the length of the new array. The only difference is that the insertion position is different.

Const ARR = [1, 2, 3= Arr.push (4, 5); // arr: [1, 2, 3, 4, 5]; Length:5

The push and Unshift methods are universal and can be done by calling () or the Apply () method call to merge two arrays.

Const VEGETABLES = [' parsnip ', ' potato '= [' celery ', ' beetroot '//  merge the second array into the first array // equivalent to Vegetables.push (' celery ', ' beetroot '); Array.prototype.push.apply (vegetables, morevegs); or [].push.apply (vegetables, morevegs); // vegetables: [' parsnip ', ' potato ', ' celery ', ' beetroot ']
12. array.reduce(callback[, initialValue]);

Each element in an array (left-to-right) executes the callback function summation, reducing it to a single value.

Const TOTAL = [0, 1, 2, 3].reduce (sum, value) = = {  returnSum +value;},0);//Total is 6Const flattened= [[0, 1], [2, 3], [4, 5]].reduce ((A, b) = = {  returnA.concat (b);}, []);//flattened is [0, 1, 2, 3, 4, 5] //initialvalue Accumulator Initial value, callback function definition:functionCallback (accumulator, CurrentValue, Currentindex, array) {}accumulator represents the value of the accumulator, when initialized, if InitialValue has a value, The value of the accumulator initialization is initialvalue, the entire loop starts with the first element, and InitialValue has no value, then the value of the accumulator initialization is the value of the first element of the array, currentvalue the value of the second element of the array, The entire loop starts with the second element.  The data type of the InitialValue can be any type and does not need to be consistent with the element value types in the original array. Const NewArray= [{name: ' AA ', age:1}, {name: ' BB ', age:2}, {name: ' cc ', Age:3}].reduce (arr, Element) = {  if(Element.age >= 2) {Arr.push (element.name); }  returnArr//there must be a return, because the return value will be assigned to the new accumulator, otherwise the value of the accumulator will be undefined. }, []); //newarray is ["BB", "CC"];the equivalent of the above code: const NewArray= [{name: ' AA ', age:1}, {name: ' BB ', age:2}, {name: ' cc ', Age:3}].filter (element = Element.age >= 2). Map (i TEM =item.name);//newarray is ["BB", "CC"];for the special use of reduce, it is similar to omitting a variable initialization step, then modifying the variable with the return of each callback, and finally returning the value of the final variable, similar to a variable declaration+a foreach execution procedure. Const NewArray= []; [{Name:' AA ', age:1}, {name: ' BB ', age:2}, {name: ' cc ', Age:3}].foreach (item = { if(Item.age >=2) {Newarray.push (item.name);}});
array.reduceRight()

Use ibid, opposite to reduce () execution direction

13. array.reverse();

Reverses the position of the elements in the array.

[' One ', ' both ', ' three '].reverse (); // [' Three ', ' one ', ' one '], the original array is flipped
14. array.slice(begin, end)

Returns a new array containing all elements of the original array from begin to end (without end) index position.

Const NewArray = [' zero ', ' one ', ' one ', ' Three '].slice (1, 3); // NewArray: [' One ', ' both '];
15. array.some(callback[, thisArg]);

Determines whether an array contains elements that can be tested by callback, and unlike every, this returns true if an element passes the test. Callback definition Ibid.

[2, 5, 8, 1, 4].some (item = item > 6); // true
16. array.sort([compareFunction]);

The elements in an array are sorted, and when comparefunction does not exist, the element is sorted by the Unicode bits of the characters converted to the string, with caution! Be sure to add the Comparefunction function when you use it, and the ordering is not stable.

[1, 8, 5].sort ((A, b) + =  {return//  from small to large }); // [1, 5, 8]
17. array.splice(start[, deleteCount, item1, item2, ...]);

Change the contents of an array by deleting existing elements and/or adding new elements. Start: Specifies the start position of the modification; DeleteCount: The number of elements to delete from the start position; Item ... : The element to be added into the array, starting at the start position.

The return value is an array of elements that are deleted. If only one element is deleted, an array containing only one element is returned. If no element is deleted, an empty array is returned.

If DeleteCount is greater than the total number of elements after start, the element after start will be deleted (with the start bit).

Const MyFish = [' Angel ', ' clown ', ' Mandarin ', ' sturgeon '//  insert ' drum ' at index 2 MyFish changed to ["Angel", "clown", "drum", "Mandarin", "sturgeon"],deleted for []

18. Other

array.copyWithin(target, start [, end = this.length])"There is a compatibility issue"
The substitution operation within the array, that is, the replacement element and the substituted element are all elements within the array
Parameters are integers, allowing start,end to be negative (nth of the penultimate)

array.fill(value [,statrt = 0[, end = this.length]])
Replace the values of all elements of the specified interval in the array with value
Start,end allowed for negative values, IBID.

array.toString()
Returns a string that consists of the ToString () return value of each element in the array, which is concatenated (separated by commas) by calling the join () method.

var arr = [' abc ', 2, {A: ' Test '}] Console.log (Arr.tostring ())        //' Abc,2,[object Object] '

array.toLocaleString()
Returns a string representing the elements in the array. The elements in the array are converted to strings using their own tolocalestring method, separated by a string of a locale-specific character, such as a comma.

array.forEach((v, i, a) => {})
Let each item of an array execute a given function once
V represents the value of the current item, I represents the current index, and a represents the array itself
The scope of the foreach traversal is determined before the first call to callback. Items added to the array after the call to foreach are not accessed by callback. If a value that already exists is changed, the value passed to callback is the value that the foreach iterates over to their moment. Deleted items are not traversed to.

array.entries()
Returns an array iterator object that contains the key-value pairs for each index in the array

var arr = ["A", "B", "C"]; var earr =//  [0, "a"]//  [1, "B"]//  [2, "C"]

array.keys()
An iterator that returns an array index (similar to the Array.entries () method)

ES6 common array Operations and tips summary

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.