Previous words
The array is a basic JS object, and as time progresses, the rest of JS is evolving, and until the ES5 standard introduces some new methods to simplify the use of the array object. The ES6 standard continues to improve the array, adding many new features. This article describes in detail the ES6 array extension
Create an array
Before ES6, there are two main ways to create arrays, one is to call the array constructor, and the other is to use the array literal syntax, both of which need to enumerate the elements in the array, which are very limited in functionality. If you want to convert a class array object (an object with a numeric index and a length property) to an array, the optional method is also very limited, and you often need to write extra code. To further simplify the creation of JS arrays, ES6 has added the Array.of () and Array.from () two methods
"Array.of ()"
ES6 added a new creation method to JS to help developers circumvent the bizarre behavior of creating arrays with the array constructor
Let items =NewArray (2); Console.log (items.length); //2Console.log (Items[0]);//undefinedConsole.log (Items[1]);//undefinedItems =NewArray ("2"); Console.log (items.length); //1Console.log (Items[0]);//"2"Items =NewArray (1, 2); Console.log (items.length); //2Console.log (Items[0]);//1Console.log (Items[1]);//2Items =NewArray (3, "2"); Console.log (items.length); //2Console.log (Items[0]);//3Console.log (Items[1]);//"2"
If you pass a numeric value to the array constructor, the length property of the array is set to that value. If multiple values are passed in, they become elements of the array, regardless of whether the values are numeric. This feature is confusing, it is impossible to always pay attention to the type of incoming data, so there is a certain risk
ES6 solves this problem by introducing the Array.of () method. Array.of () is similar to the array constructor, except that there is no special case of a single numeric parameter value, regardless of the number of arguments, regardless of the type of argument, the Array.of () method always creates an array containing all the arguments.
Let items = Array.of (1, 2 // 2 console.log (Items[0]); // 1 console.log (items[1]); // items = array.of (2 // 1 console.log (items[0]); // items = Array.of (" 2 " // 1 console.log (items[0]); //
To create an array with the Array.of () method, simply pass in the values you want to include in the array. The first example creates an array with two numbers, the second array contains a number, and the last array contains a string. This is similar to how the array literal is used, and most of the time you can create a primitive array with an array literal, but if you need to pass a function into the array's constructor, you might prefer to pass in array.of () to ensure consistent behavior
function Createarray (Arraycreator, value) { return= Createarray (array.of, value);
In this Code center the Createarray () function takes two parameters, one is the array creator function and the other is the value to insert the array into. You can pass in Array.of () as the first parameter of the Createarray () method to create a new array, and if it is not guaranteed that the incoming value must not be a number, passing in the array directly is dangerous
Note The Array.of () method does not determine the type of the return value through the Symbol.species property, it uses the current constructor (the this value in the of () method) to determine the correct type of return data
"Array.from ()"
JS does not support directly converting non-array objects to real arrays, arguments is a class array object, and if you want to use it as an array, you must first convert the object's type. In ES5, it may be necessary to write the following function to convert the class array object to array
function Makearray (arraylike) { var result = []; for (var i = 0, len = arraylike.length; i < Len; i++) { result.push (arraylike[i]); } return result;} function dosomething () { var args = makearray (arguments); // use args}
This method first creates a result array manually, and then copies each element in the arguments object into the new array. Although this approach works, you need to write a lot of code to accomplish such a simple operation. Eventually, developers discovered a new way to write very little code, calling the array native slice () method to convert non-array objects to arrays
function Makearray (arraylike) { return Array.prototype.slice.call (arraylike);} function dosomething () { var args = makearray (arguments); // use args}
The function of this code is equivalent to the previous example, when the slice () method executes the This value is set to the class array object, and the slice () object only needs the numeric index and the length property to be able to run correctly, so any class array object can be converted to arrays
Although this technique does not need to write a lot of code, we cannot intuitively think of this as converting arraylike to an array when we call Array.prototype.slice.call (Arraylike). Fortunately, ES6 added a new method of semantic clarity and simple syntax array.from () to convert an object into an array
The Array.from () method can accept an iterator to an object or class array object as the first parameter and eventually return an array
function dosomething () { var args = array.from (arguments); // use args}
The Array.from () method call creates a new array based on the elements in the arguments object, and args is an instance of the array that contains the same value in the same position as the arguments object
Note The Array.from () method also uses this to determine the type of the returned array.
Mapping transformations
If you want to further convert the array, you can provide a mapping function as the second parameter of Array.from (), which is used to convert each value in the class array object to another form, and finally store the results in the corresponding index of the result array
function translate () { return array.from (arguments, (value) = + value +1 = translate (1, 2, 3 // 2,3,4
In this code, for the Array.from () method to pass in the mapping function (value) =>value+1, each element in the array is added 1 before it is stored. If you use a mapping function to process an object, you can also pass the third parameter to the Array.from () method to represent the this value of the mapping function
Let helper = { 1, Add (value) { returnthis. diff; }}; function translate () { return= Translate (1, 2, 3// 2,3,4
This example passes in Helper.add () as a mapping function for the transformation, because the method uses the This.diff property, so the Array.from () method needs to be provided with a third argument to specify the value of this, eliminating the need to call bind () method or other way to specify the value of this
Use Array.from () to convert an object to iteration
The Array.from () method can handle the class array object and the iterator object, which means that the method can convert all objects that contain the Symbol.iterator property to the arrays
Let numbers = { *[Symbol.iterator] () { 1; 2; 3; = Array.from (Numbers, (value) = = value +1// 2,3,4
Since numbers is an iterative object, it can be passed directly to Array.from () to convert an array. The mapping function here adds 1 to each number, so the resulting array eventually contains values of 2, 3, and 4
[note] If an object is both an array of classes and an iterative one, then the Array.from () method determines which value to convert based on the iterator
Array method
ES6 continues the ES5 's consistent style and adds several new methods to the array. The Find () method and the FindIndex () method can assist the developer in finding arbitrary values in the array, and the fill () method and the Copywithin () method are inspired by the use of the training array, which is also a new feature in the ES6, an array containing only numbers
"Find () and FindIndex ()"
Since there is no built-in array search method, ES5 formally adds the indexof () and LastIndexOf () two methods that can be used to find specific values in the array. While this is a huge improvement, the two approaches still have limitations, that is, you can only find one value at a time, and if you want to find the first even number in a series of numbers, you must write your own code to implement it. So ES6 introduced the Find () method and the FindIndex () method to solve the problem.
Both the Find () method and the FindIndex () method accept two parameters: one is the callback function and the other is an optional parameter that specifies the value of this in the callback function. When you execute a callback function, the parameters passed in are the same as an element in the array, the index of the element in the arrays, and the group itself, as the parameters of the incoming map () and the foreach () method. If the given value satisfies the defined criteria, the callback function should return true. Once the callback function returns the True,find () method and the FindIndex () method stops searching the remaining parts of the array immediately
The only difference between the two is that the Find () method returns the value found, the FindIndex () method returns the index of the value found
Let numbers = [+, +, +, - 2
This code calls the Find () method and the FindIndex () method to locate the first value in the numbers array that is greater than 33, and the call to the Find () method returns 35, whereas the call to the FindIndex () method returns the 35 position in the Numbeps array 2
The Find () method and the FindIndex () method can do a good job of finding matching elements in an array based on a condition, and the IndexOf () method and the LastIndexOf () method are a better choice if you want to find only the elements that match a value
"Fill ()"
The Fill () method fills a maximum number of array elements with the specified value. When a value is passed in, the Fill () method overrides all values in the array with this value
Let numbers = [1, 2, 3, 4];numbers.fill (1// 1,1,1,1
In this example, when you call the Numbers.fill (1) method, all the values in numbers become 1, and if you want to change only the value of one part of the array, you can pass in both the start index and the two optional parameters that do not contain the end index (without the current value of the end index)
Let numbers = [1, 2, 3, 4];numbers.fill (1, 2// 1,2,1,1numbers.fill (0, 1, 3) c5>// 1,0,0,1
In the Numbers.fill call, the parameter 2 means that the element is populated starting at index 2, because the third argument is not passed as a no-end index, so the last two elements of the numbers array are filled with 1 because the numbers.length is not included as the end index. The action Numbers.fill (0,1,3) populates the elements in the array with indexes 1 and 2 as 0. When you call Fill (), the second and third arguments can be populated with only a subset of the elements in the array
[note] If the start index or end index is negative, the values are added to the array's length property as the final position. For example, if the start position is-1, then the value of the index is actually array.length-1,array to the array calling the Fill () method
"Copywithin ()"
The Copywithin () method is similar to the Fill () method, and it can also change multiple elements in the array at the same time. The Fill () method assigns the array element to a specified value, while the Copywithin () method copies the value of the element from the array. You need to pass in two arguments when calling the Copywithin () method: One is the index where the method begins to populate the value, and the other is the index where the value is to begin copying
such as copying the value of the first two elements of an array to the last two elements
Let numbers = [1, 2, 3, 4]; // start pasting from the position of index 2 // copying data starting from the position of the array index 0 numbers.copywithin (2, 0// 1,2,1,2
This code pastes values starting at index 2 of numbers, so indexes 2 and 3 are rewritten. Pass the second parameter 0 to Copywithin () to indicate that the value is copied from index 0 and lasts until there are no more replicable values
By default, Copywithin () copies the values until the end of the array, but can provide an optional third parameter to limit the number of overridden elements. The third parameter is no end index, which specifies where to stop copying values
Let numbers = [1, 2, 3, 4]; // start pasting from the position of index 2 // copying data starting at the position of the array index 0 // stop copying when you encounter index 1 o'clock Numbers.copywithin (2, 0,1// 1,2,1,4
In this example, because the optional end index is set to 1, only the value at index 0 is copied, and the last element in the array remains unchanged
[note] As with the fill () method, all parameters of the Copywithin () method accept negative values and are automatically added to the length of the array as the end-use index
The two methods of Fill () and Copywithin () originate from the training array and are added to the regular array in order to preserve the consistency of the array methods. If you use a trained array to manipulate the bits of a number, these methods will
ES6 Array Extension