ECMAScript6 will bring us new array operation method foresight _ javascript skills

Source: Internet
Author: User
This article mainly introduces the future of ECMAScript6's new array operation method. if you need it, refer to this article to introduce ECMAScript 6's new array operation method, and how to apply these new array features in an existing browser.

Note: I will use two terminologies, constructor and class.

Class method
Array methods.

Array. from (arrayLike, mapFunc ?, ThisArg ?)

The basic function of Array. from () is to convert two types of objects into arrays.

Array-like objects)

This type of object has the attributes of length and index. The result of the DOM operator belongs to this class, for example, document. getElementsByClassName ().

Iterable objects)

This type of object can only take one element at a time. Arrays can be iterated, such as the new array structure, Map, and Set in ECMAScript ).

The following code is an example of converting an array object to an array:

The code is 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 into an array before using this method.

Use Mapping through Array. from ()
Array. from () is also an alternative to generic map.

The code is 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 both methods is the arrow function ).
In this example, the result of document. querySelectorAll () is a class array object instead of an array. This is why we cannot directly call map. In the first example, in order to use forEach (), we convert the class array object into an array. Here we use the generic method and two parameter versions of Array. from (), while eliminating the intermediate steps.

Holes
Array. from () ignores the missing element-hole (holes) in the Array, which is treated with undefined elements.

The code is as follows:


> Array. from ([0, 2])
[0, undefined, 2]

This means that you can use Array. from () to create or fill an Array:

The code is as follows:


> Array. from (new Array (5), () => 'A ')
['A', 'A']
> Array. from (new Array (5), (x, I) => I)
[0, 1, 2, 3, 4]

If you want to fill an Array with a fixed value, Array. prototype. fill () (see the following) is a better choice. The first is the two methods in the preceding example.

From () in the Array (Array) subclass ()
Another application scenario of Array. from () is to convert an Array object of the class or an instance of the iterated object to an Array subclass. If you create an Array subclass MyArray and want to convert this type of object to an instance of MyArray, you can simply use MyArray. from (). The reason for this is that constructors in ECMAScript 6 will inherit (the parent class constructor is the prototype of its subclass constructor )).

The code is as follows:


Class MyArray extends Array {
...
}
Let instanceOfMyArray = MyArray. from (anIterable );

You can combine this function with mapping to complete the opering operation in a place where you control the result constructor ):

The code is as follows:


// From ()-determine the result's constructor via the aggreger
// (In this 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 into an array, you should use array source text (array literal ). In particular, when there is only one value and it is still a number, the array constructor strikes. For more information, see.

The code is as follows:


> New Array (3, 11, 8)
[3, 11, 8]
> New Array (3)
[,]
& Gt; new Array (3.1)
RangeError: Invalid array length

What should we do if we want to convert a group of values to an instance of the sub-constructor? This is the value of Array. of () (remember, the Array sub-constructor inherits all Array methods, including ()).

The code is as follows:


Class MyArray extends Array {
...
}
Console. log (MyArray. of (3, 11, 8) instanceof MyArray); // true
Console. log (MyArray. of (3). length = 1); // true

Nested values in an Array, Array. of () is quite convenient, and there is no way to handle Array. However, pay attention to Array. prototype. map (), which has the following pitfalls:

The code is as follows:


> ['A', 'B']. map (Array.)
[['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 this case)
[['A'], ['B']

As you can see, map () will pass three parameters to its callback. The last two are often ignored (in detail ).

Prototype methods)
There are many new methods available for array instances.

Iteration in the array (Iterating over arrays)

The following methods help to complete the iteration in the array:

The code is as follows:


Array. prototype. entries ()
Array. prototype. keys ()
Array. prototype. values ()

Each of the preceding methods returns a string of values, but not an array. They are displayed one by one through the iterator. Let's look at an example (I will use Array. from () to put the content of the iterator in an Array ):

The code is 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 combine the for-of loop in entries () and ECMAScript 6 to conveniently split the iteration object into key-value pairs:

The code is as follows:


For (let [index, elem] of ['A', 'B']. entries ()){
Console. log (index, elem );
}

Note: This code can be run in the latest Firefox browser. T Firefox.

Search for array elements

Array. prototype. find (predicate, thisArg ?) The first element that meets the callback function is returned. If no element meets the condition, it returns undefined. For example:

The code is 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 meets the callback function. If no satisfied element is found,-1 is returned. For example:

The code is as follows:


> [6,-5, 8]. findIndex (x => x <0)
1
> [6, 5, 8]. findIndex (x => x <0)
-1

Both find * methods ignore holes, that is, they do not focus on undefined elements. The callback completion function signature is:

Predicate (element, index, array)
Use findIndex () to find NaN

Array. prototype. indexOf () has a well-known limitation that NaN cannot be searched. Because it uses constant equals (=) to find matching elements:

The code is as follows:


> [NaN]. indexOf (NaN)
-1

With findIndex (), you can use Object. is (), which will not produce the following problems:

The code is as follows:


> [NaN]. findIndex (y => Object. is (NaN, y ))
0

You can also use a more general method to create a help function elemIs ():

The code is as follows:


> Function elemIs (x) {return Object. is. bind (Object, x )}
> [NaN]. findIndex (elemIs (NaN ))
0
Array. prototype. fill (value, start ?, End ?)

Fill in an array with the given value:

The code is as follows:


> ['A', 'B', 'C']. fill (7)
[7, 7, 7]

Holes do not have any special treatment:

The code is as follows:


> New Array (3). fill (7)
[7, 7, 7]

You can also limit the start and end of filling:

The code is as follows:


> ['A', 'B', 'C']. fill (7, 1, 2)
['A', 7, 'C']

When can I use the new array method?
Some methods can be used in the browser.

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.