This article describes ECMAScript 6, which is about to bring us new array manipulation methods and how to apply these new array features to existing browsers.
Note: I will use the alternating constructor (constructor) and Class (class) two terms.
Class method
The method owned by the array itself.
Array.from (Arraylike, Mapfunc, Thisarg?)
The basic function of Array.from () is to convert the two types of objects into groups.
Class Array Object (Array-like objects)
The class object has attributes of length and index. The result of the DOM operator belongs to the class, such as Document.getelementsbyclassname ().
Iteration Objects (Iterable objects)
This type of object can only take one element at a time when it takes a value. Arrays are iterative, like the new array structure in ECMAScript, the map (map), and set (set).
The following code is an example of a transformation class array object to an array:
Copy Code code as follows:
Let lis = Document.queryselectorall (' ul.fancy li ');
Array.from (LIS). ForEach (Function (LI) {
Console.log (node);
});
The result of Queryselectorall () is not an array, and there is no foreach () method. This is why we need to convert it to an array before using this method.
Use mapping via Array.from ()
Array.from () is also a generic alternative to using map ().
Copy Code code as follows:
Let spans = document.queryselectorall (' Span.name ');
Map (), generically:
Let names1 = Array.prototype.map.call (spans, S => s.textcontent);
Array.from ():
Let Names2 = Array.from (spans, S => s.textcontent);
The second parameter in the two method is an arrow function.
In this example, the result of Document.queryselectorall () is a class array object, not an array. That's why we can't call map () directly. In the first example, in order to use foreach (), we converted the class array object to an array. Here we omit the intermediate step by using the generic method and the two-parameter version of Array.from ().
Holes
Array.from () ignores the missing element-hole (holes) in the array, and treats it as an undefined element (undefined elements).
Copy Code code as follows:
> Array.from ([0,,2])
[0, Undefined, 2]
This means that you can use Array.from () to create or populate an array:
Copy Code code as follows:
> Array.from (New Array (5), () => ' a ')
[' A ', ' a ', ' a ', ' a ', ' a ']
> Array.from (New Array (5), (x,i) => i)
[0, 1, 2, 3, 4]
If you want to populate an array with a fixed value, then Array.prototype.fill (see below) will be a better choice. The first one is the two ways of the example above.
From () in a subclass of an array (array)
Another use scenario for Array.from () is to convert an array object or an iteration object to an instance of an array (array) subclass. If you create a subclass of an array myarray, and you want to convert such objects into an instance of myarray, you can simply use Myarray.from (). This can be used because the constructor (constructors) in ECMAScript 6 inherits (the parent constructor is the prototype of its subclass constructor (prototype)).
Copy Code code as follows:
Class MyArray extends Array {
...
}
Let Instanceofmyarray = Myarray.from (aniterable);
You can combine this function with the mapping (mapping) to complete the mapping operation (map operation) in a place where you control the result builder:
Copy Code code as follows:
From () –determine the "result" constructor via the receiver
(In the case, myarray)
Let Instanceofmyarray = Myarray.from ([1, 2, 3], x => x * x);
Map (): The result is always an instance of Array
Let Instanceofarray = [1, 2, 3].map (x => x * x);
Array.of (... items)
If you want to convert a set of values to an array, you should use the source text (array literal). In particular, when there is only one value and still a number, the constructor of the array strikes. For more information, please refer to.
Copy Code code as follows:
> New Array (3, 11, 8)
[3, 11, 8]
> New Array (3)
[ , , ,]
> New Array (3.1)
Rangeerror:invalid Array length
What should we do if we want to convert a set of values into an instance of a digital sub-constructor? This is the value of the Array.of () (Remember, the array sub constructor inherits all of the array methods, including, of course, the ()).
Copy Code code as follows:
Class MyArray extends Array {
...
}
Console.log (Myarray.of (3, one, 8) instanceof myarray); True
Console.log (Myarray.of (3). length = = 1); True
Nesting value packages in an array, array.of () can be quite handy, without an array () as bizarre as the way it is handled. But also pay attention to Array.prototype.map (), here are pits:
Copy Code code as follows:
> [' A ', ' B '].map (array.of)
[[' A ', 0, [' A ', ' B ']],
[' B ', 1, [' A ', ' B ']]]
> [' A ', ' B '].map (x => array.of (x))//Better
[[' A '], [' B ']]
> [' A ', ' B '].map (x => [x])//Best (in the case)
[[' A '], [' B ']]
As you can see, map () passes three parameters to its callback. The last two are often ignored (in detail).
Prototype method (Prototype methods)
An instance of an array can have many new methods available.
Iteration in array (iterating over arrays)
The following methods will help you complete the iteration in the array:
Copy Code code as follows:
Array.prototype.entries ()
Array.prototype.keys ()
Array.prototype.values ()
Each of these methods returns a string of values, but does not return as an array. They are displayed through iterators, one after the other. Let's look at an example (I'll use Array.from () to put the contents of the iterator in an array):
Copy Code code as follows:
> Array.from ([' A ', ' B '].keys ())
[0, 1]
> Array.from ([' A ', ' B '].values ())
[' A ', ' B ']
> Array.from ([' A ', ' B '].entries ())
[[0, ' a '],
[1, ' B ']]
You can easily disassemble an iterative object into a Key-value pair by combining the for-of loops in entries () and ECMAScript 6:
Copy Code code as follows:
for (let [index, Elem] of [' A ', ' B '].entries ()) {
Console.log (index, elem);
}
Note: This code can already be run in the latest Firefox browser. T Firefox.
Find array elements
Array.prototype.find (predicate, thisarg) returns the first element that satisfies the callback function. If no element satisfies the condition, it returns undefined. Like what:
Copy Code code as follows:
> [6, -5, 8].find (x => x < 0)
-5
> [6, 5, 8].find (x => x < 0)
Undefined
Array.prototype.findIndex (predicate, thisarg?)
Returns the index of the first element that satisfies the callback function. Returns-1 if no element is found to be satisfied. Like what:
Copy Code code as follows:
> [6, -5, 8].findindex (x => x < 0)
1
> [6, 5, 8].findindex (x => x < 0)
-1
Two find* methods ignore the hole (holes), which is not concerned with undefined elements. The completion function signature of the callback is:
predicate (element, index, array)
Find Nan by FindIndex ()
Array.prototype.indexOf () has a well-known limitation that it is not possible to find Nan. Because it finds the matching element with identity (= = =):
Copy Code code as follows:
Using FindIndex (), you can use Object.is (), which does not create such a problem:
Copy Code code as follows:
> [Nan].findindex (Y => object.is (NaN, y))
0
You can also use a more general way of creating a Help function Elemis ():
Copy Code code as follows:
> Function ElemIs (x) {return Object.is.bind (Object, X)}
> [Nan].findindex (ElemIs (NaN))
0
Array.prototype.fill (value, start, end?)
Fills an array with the given value:
Copy Code code as follows:
> [' A ', ' B ', ' C '].fill (7)
[7, 7, 7]
The cave (holes) will not have any special treatment:
Copy Code code as follows:
> New Array (3). Fill (7)
[7, 7, 7]
You can also limit the start and end of your fill:
Copy Code code as follows:
> [' A ', ' B ', ' C '].fill (7, 1, 2)
[' A ', 7, ' C ']
When can I use the new array method?
Some methods are already available in the browser.